2

I'm pretty much a beginner working with Python so I apologize if I use the wrong terminology. I have a question regarding stem plots using matplotlib. I want to plot the frequency of change on certain positions on a object. I have this pandas dataframe:

df = pd.DataFrame([
('315', '1',),
('497', '1',),
('615', '1',),
('646', '1',),
('729', '1',),
('803', '1',),
('882', '3',)
], columns=['position', 'freq'])

df

  position freq
0      315    1
1      497    1
2      615    1
3      646    1
4      729    1
5      803    1
6      882    3

Now I want to make a stem plot like this:

plt.stem(df.position,df.freq)  

enter image description here

However the positions in the dataframe is actually part of a larger range of values from 0-912 (the total length of the object). I want the stem plot to include these values on the x-axis to create a plot looking something like this:

enter image description here

Disregarding the color marked boxes on the axis and the way the plot is displayed, I only want to include the full range of x-values (0-912 and displaying the positions in the dataframe).

Dr. Brynjolf
  • 53
  • 1
  • 7
  • does your dataframe contain info somewhere to determine the range (0, 912)? If not, you can simply hard-code it with `plt.xlim(0, 912)`. But it is better to set a range from data if possible – Bonlenfum Oct 26 '18 at 09:10
  • @Bonlenfum I only know know that the positions in the dataframe are changed, the other positions from 0-912 that are not in the dataframe should have freq=0. Should i add every single value to the dataframe or is there another way of doing it? `plt.xlim(0, 912)` does not seem to work right away, the plotted values are not distributed right along the axis. – Dr. Brynjolf Oct 26 '18 at 10:13

1 Answers1

2

I now realized that the position values were strings and not integers. Problem solved!

Dr. Brynjolf
  • 53
  • 1
  • 7
  • glad you solved it! Yes, text is not automatically interpreted as numerical. With a bit of massaging you could still do it, eg `plt.stem(df.position.values.astype(float), df.freq)`, if you couldn't update the original data generation. – Bonlenfum Oct 26 '18 at 11:28