pandas 如何绘制数据帧?在 Python 中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37841496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:24:13  来源:igfitidea点击:

How to plot DataFrames? in Python

pythonpandasplotdataframe

提问by PAstudilloE

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)

我正在尝试绘制 DataFrame,但没有得到我需要的结果。这是我正在尝试做的事情以及我目前正在得到什么的一个例子。(我是 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!!.

我得到了下图,但我需要的是:X 轴上的年份,每条线必须是 X 轴(a、b、c、d)中当前的年份。谢谢你的帮助!!。

enter image description here

在此处输入图片说明

回答by MaThMaX

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

在此处输入图片说明

回答by MaxU

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

在此处输入图片说明