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

Question:

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

Asked By: muckywater

||

Answers:

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

Answered By: Chris

This works for me:

import numpy as np
import matplotlib.pyplot as plt
 
quiz = True
data = {}

while quiz:
    programming_language = input("What programming language you like?")
    score = int(input("Score?"))
    data[programming_language] = score
    continue_quiz = input("Continue?[y/n]")
    if continue_quiz == 'y':
        quiz = True
    else:
        quiz = False

languages = list(data.keys())
values = list(data.values())
  
fig = plt.figure(figsize = (10, 5))
 
# creating the bar plot
plt.bar(languages, values, color ='maroon',
        width = 0.4)
 
plt.xlabel("Programming Language")
plt.ylabel("Score")
plt.title("Score your favorite programming")
plt.show()
  1. You’re trying to use str to plot numerical values – they need to be converted
  2. You need to split datay so that you have x number of values to plot, not one string of multiple numbers
  3. After doing the above when you use heights = (datay) it converts the integer values back into str

Hope this helps

Answered By: thelogansno22