3

I'm trying to plot a DataFrame, but I'm not getting the results I need. This is an example of what I'm trying to do and what I'm currently getting. (I'm new in Python)

import pandas as pd
import matplotlib.pyplot as plt

my_data = {1965:{'a':52, 'b':54, 'c':67, 'd':45}, 
      1966:{'a':34, 'b':34, 'c':35, 'd':76}, 
      1967:{'a':56, 'b':56, 'c':54, 'd':34}}  

df = pd.DataFrame(my_data)
df.plot( style=[])
plt.show()

I'm getting the following graph, but what I need is: the years in the X axis and each line must be what is currently in X axis (a,b,c,d). Thanks for your help!!.

enter image description here

3
  • Could you maybe expand on what isn't working right? It isn't totally clear what you want the x-axis to look like. Commented Jun 15, 2016 at 17:03
  • Hi kikpatty... what I need is to have a plot that shows the years (1965, 1966,1967) in the X axis and each line will be a,b,c and d. For example, the blue line to be 'a', the green "b" and the red "c". Does it make sense? Commented Jun 15, 2016 at 17:07
  • It does. You may want to edit your question to clear that up for anyone else. Commented Jun 15, 2016 at 17:14

2 Answers 2

2
import pandas as pd
import matplotlib.pyplot as plt

my_data = {1965:{'a':52, 'b':54, 'c':67, 'd':45}, 
      1966:{'a':34, 'b':34, 'c':35, 'd':76}, 
      1967:{'a':56, 'b':56, 'c':54, 'd':34}}  

df = pd.DataFrame(my_data)
df.T.plot( kind='bar') # or df.T.plot.bar()
plt.show()

enter image description here


Updates:

If this is what you want:

df = pd.DataFrame(my_data)
df.columns=[str(x) for x in df.columns] # convert year numerical values to str
df.T.plot()
plt.show()

enter image description here

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks!... that I need is the same graph but as a "line plot", but when I do this, I can't see the years in the Y Axis.
Does changing kind='bar' to kind='line' solve this issue?
@PabloA.AstudilloEstévez, what d you mean "you cannot see years in the Y Axis". I'm plotting it as x-axis as mentioned in your question
@kirkpatt, when I do that I get "0, 0.5, 1, 1.5, 2 +1.965e3" in the X Axis.
Sorry @MaThMaX, I meant X Axis.
|
1

you can do it this way:

ax = df.T.plot(linewidth=2.5)

plt.locator_params(nbins=len(df.columns))

ax.xaxis.set_major_formatter(mtick.FormatStrFormatter('%4d'))

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.