python - Pandas 从数据透视表绘图

标签 python python-3.x pandas matplotlib pivot-table

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

我通过以下方式从我的 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/

相关文章:

python-3.x - Python : does Gevent 1. 0 支持 Python 3.3?

python - groupby 并对两列求和并在 pandas 中设置为一列

python - 计算每一行的大写字母

python - 字典作为 kwargs ,其变量多于使用的变量

python - 在 MNIST 数据集上训练的 DC GAN 的 Frechet Inception Distance

java - 我训练的图像分类器模型对所有不属于该类别的图像进行分类

python - 删除重复项,但保留每组给定列中具有最大值的行

python - Urllib2 Python - 重新连接和拆分响应

python - 通过将不同数据帧中具有相同索引的两列相乘来添加新列

python-3.x - 多线程异步s3调用增加了内存python