This script takes a .csv file and allows the user to specify which columns will be the x and y variables in the plot. It saves the plot as a .png in the working directory.
# barchart_generator.py
# By: Sylvia Shea
# Version 1.0
# Last Edit: 2020-09-03
# Purpose: This script takes a .csv file and allows the
# user to specify the x and y variables to be plotted.
# It saves the figure as a .png.
####################
# Required Modules #
####################
import matplotlib.pyplot as plt
import pandas as pd
import argparse
import sys
####################
# Function #
####################
def generate_barchart(df,x_col,y_col,title):
= 'Sathu'
fontname = 'cornflowerblue'
color # Fig specs
= plt.subplots()
fig, ax =16,fontname=fontname)
ax.set_ylabel(y_col,fontsize=16,fontname=fontname)
ax.set_xlabel(x_col,fontsize='x',labelsize=12)
ax.tick_params(axis='y',labelsize=12)
ax.tick_params(axisfor i in ['top','right']:
False)
ax.spines[i].set_visible(# Bar plot
=df[x_col], height=df[y_col], color=color)
ax.bar(x=20,fontname=fontname)
ax.set_title(title,fontsize='tight', dpi=1000)
plt.savefig(title, bbox_inches
def main():
= 'y'
res while res == 'y':
'Notice: Output is the same name as title and placed in working directory')
sys.stdout.write('\n---------------------------')
sys.stdout.write('Input CSV name (include .csv) ')
sys.stdout.write(
sys.stdout.flush()= input()
path
try:
= pd.read_csv(path)
df except FileNotFoundError:
print('File not found!')
'Here are your columns: ')
sys.stdout.write(print('\n---------------------------')
= list(df.columns)
columns print(str(i + 1) + ': ' + col) for i,col in enumerate(columns)]
['Input number for x value ')
sys.stdout.write(
sys.stdout.flush()= int(float(input())) - 1
x_key = columns[x_key]
x_col
'Input number for y value ')
sys.stdout.write(
sys.stdout.flush()= int(float(input())) - 1
y_key = columns[y_key]
y_col
'Input title (will also be the name of the .png file) ')
sys.stdout.write(= str(input())
title
# Plot
print('\n-------------------'
'Generating Plot'
'-------------------')
generate_barchart(df,x_col,y_col,title)print('\n-------------------'
'Plot Generated!'
'-------------------')
'\nContinue? (y/n): ')
sys.stdout.write(
sys.stdout.flush()= input()
res
####################
# Main #
####################
if __name__ == "__main__":
= argparse.ArgumentParser(description='Make a barchart from CSV')
parser = parser.parse_args()
args main()