gpt4 book ai didi

python - Pandas 从数据透视表绘图

转载 作者:太空狗 更新时间:2023-10-30 00:48:48 24 4
gpt4 key购买 nike

我基本上是在尝试重现显示不同地点全年平均温度和降水量的气候图。

我通过以下方式从我的 csv 生成了一个数据透视表:

data = pd.read_csv("05_temp_rain_v2.csv")
pivot = data.pivot_table(["rain(mm)","temp(dC)"], ["loc","month"])

文本形式的示例数据:

loc,lat,long,year,month,rain(mm),temp(dC)
Adria_-_Bellombra,45.011129,12.034126,1994,1,45.6,4.6
Adria_-_Bellombra,45.011129,12.034126,1994,2,31.4,4
Adria_-_Bellombra,45.011129,12.034126,1994,3,1.6,10.7
Adria_-_Bellombra,45.011129,12.034126,1994,4,74.4,11.5
Adria_-_Bellombra,45.011129,12.034126,1994,5,26,17.2
Adria_-_Bellombra,45.011129,12.034126,1994,6,108.6,20.6

数据透视表:

enter image description here

因为我要处理不同的位置,所以我要遍历它们:

locations=pivot.index.get_level_values(0).unique()

for location in locations:
split=pivot.xs(location)

rain=split["rain(mm)"]
temp=split["temp(dC)"]

plt.subplots()
temp.plot(kind="line",color="r",).legend()
rain.plot(kind="bar").legend()

示例绘图输出如下所示:

enter image description here

为什么我的温度值是从二月 (2) 开始绘制的?
我认为这是因为温度值列在第二列中。

从数据透视表处理和绘制不同数据(两列)的正确方法是什么?

最佳答案

这是因为 linebar 图没有以相同的方式设置 xlim。在条形图的情况下,x 轴被解释为分类数据,而在线图的情况下,x 轴被解释为连续数据。结果是 xlimxticks 在这两种情况下的设置不同。

考虑一下:

In [4]: temp.plot(kind="line",color="r",)
Out[4]: <matplotlib.axes._subplots.AxesSubplot at 0x117f555d0>
In [5]: plt.xticks()
Out[5]: (array([ 1., 2., 3., 4., 5., 6.]), <a list of 6 Text xticklabel objects>)

其中刻度的位置是一个 float 组,范围从 1 到 6

In [6]: rain.plot(kind="bar").legend()
Out[6]: <matplotlib.legend.Legend at 0x11c15e950>
In [7]: plt.xticks()
Out[7]: (array([0, 1, 2, 3, 4, 5]), <a list of 6 Text xticklabel objects>)

其中刻度的位置是一个整数数组,范围从 0 到 5

因此,更容易替换这部分:

temp.plot(kind="line", color="r",).legend()
rain.plot(kind="bar").legend()

通过:

rain.plot(kind="bar").legend()
plt.plot(range(len(temp)), temp, "r", label=temp.name)
plt.legend()

bar line plot pandas

关于python - Pandas 从数据透视表绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36132749/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com