Search code examples
pythonlistmatplotlibgraphbar-chart

how to add user input into a bar graph and how to separate input - Python


I am trying to form a bar graph using data the user inputs. I have a proper graph made by the user input but I can't seem to insert the actual data in there. I also have a problem with separating the different terms. Here is my code:

import matplotlib.pyplot as plt

definition = input('Definition of data set: ')
datay = input('Enter Y-axis data (Integer): ')
datax = input('Enter X-axis data (Term): ')
y = input('Y-axis label: ')
x = input('X-axis label: ')

data_num = datay.split()
datalist = [round(float(a)) for a in data_num]

min_val = min(datalist)
max_val = max(datalist)

left_coordinates=[min_val, max_val]
heights= (datay)
bar_labels= [datax]
plt.bar(left_coordinates,heights,tick_label=bar_labels,width=0.6,color=['red','black'])
plt.xlabel(x)
plt.ylabel(y)
plt.title(definition)
plt.show()

Here is the input

Definition of data set: Amount of ants on different types of food
Enter Y-axis data (Integer): 4 5 10
Enter X-axis data (Term): apple mango ice-cream
Y-axis label: Amount of ants
X-axis label: Type of food

Here is the output:

Graph output


Solution

  • I believe the tick_label is causing the issue. You could try:

    import matplotlib.pyplot as plt
    
    definition = input('Definition of data set: ')
    datay = input('Enter Y-axis data (Integer): ').split()
    datax = input('Enter X-axis data (Term): ').split()
    y = input('Y-axis label: ')
    x = input('X-axis label: ')
    
    
    plt.bar(datax, height=datay, width=0.6, color=['red','black'], )
    plt.xlabel(x)
    plt.ylabel(y)
    plt.title(definition);
    

    Output

    enter image description here