Reputation: 55
Let me start by saying I know about the histogram function that just creates a nice histogram from a list of data. For this project I am trying to do everything the somewhat hard way because as far as I am concerned, more code=more practice.
Now for the meat of the question, with plenty of help I have managed to write code that extracts a data set, takes user inputs for titles and number of bins, and crunches everything accurately into a "histogram" list, something like [1,3,5,3,1]
with the numbers corresponding to the frequency of a range of data.
What I am trying to do from this point is take that histogram list and place it in a bar graph using plt.bar()
. I have some familiarity with plt.scatter()
but it seems bar works differently as
plt.bar(x, y, align='center')
plt.xticks(y)
plt.show
with x being a list containing the separation values for the bins, and y being the list of frequencies, simply returns an empty graph. any assistance would be appreciated.
Edit: code modifications:
column="voltage"
y=[14, 5, 5, 4, 3, 5, 5, 4, 6, 9] # frequencies
x=[-4.9183599999999998, -3.916083, -2.9138060000000001, -1.9115290000000003,
-0.90925200000000039, 0.093024999999999025, 1.0953019999999993,
2.0975789999999996, 3.0998559999999991, 4.1021329999999985,
5.1044099999999979] #bin limits
z=range(len(y))
plt.bar(z, y, 1.0)
plt.xlabel("%s" %column)
plt.xticks(z, x)
plt.show()
which produces:
Pretty close, eventually I'll need to round x, but before that happens, how do I get the ticks to align to the right? Also, why is the xlabel line outputting "1" instead of the string?
Upvotes: 0
Views: 147
Reputation: 51683
Youre show
is missing some ()
- and your code does not qualify as mvce.
This works:
import matplotlib.pyplot as plt
y = [1,1,4,7,4,3]
x = range(len(y))
plt.bar(x, y, 0.75, color="blue")
plt.show()
Your y and x have different dimensions, they will be cropped to the shorter one.
import matplotlib.pyplot as plt
column="voltage"
y=[14, 5, 5, 4, 3, 5, 5, 4, 6, 9] # frequencies
x=[-4.9183599999999998, -3.916083, -2.9138060000000001, -1.9115290000000003,
-0.90925200000000039, 0.093024999999999025, 1.0953019999999993,
2.0975789999999996, 3.0998559999999991, 4.1021329999999985,
5.1044099999999979] #bin limits
z=range(len(y))
plt.bar(z, y, 0.8)
plt.xlabel("%s" %column)
plt.xticks(z,[str(round(i,4)) for i in x], rotation=35) # round, label and use
plt.show()
I adjusted the subplot borders in the popup, you need to code that. How to and how to move all bars to the right so they are between the ticks, see:
Move graph position within plot (matplotlib)
Thats too much matplotmagic for me.
Upvotes: 1