Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot DataFrames? in Python

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

like image 898
PAstudilloE Avatar asked Apr 12 '26 16:04

PAstudilloE


2 Answers

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

like image 160
MaThMaX Avatar answered Apr 19 '26 00:04

MaThMaX


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

like image 42
MaxU - stop WAR against UA Avatar answered Apr 18 '26 22:04

MaxU - stop WAR against UA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!