为多个图表重用轴对象

问题描述 投票:0回答:1

我有一个带有值的pandas DataFrame和季节指标。我想为整个集创建一个密度图,然后为每个季创建一个密度图,其中应包括整体密度加上季节的密度。 由于整体密度估计需要一些时间(我有超过40000个数据点),我想避免每个季节重复一次。

到目前为止,我得到的最接近的是这个代码,基于this answer

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

n = 25
seasons = ['winter', 'spring', 'summer', 'autumn']
df = pd.DataFrame({'value': np.random.randn(n), 'season': np.random.choice(seasons, n)})

ax = df['value'].plot.density(label="all", legend=True)
plt.savefig("test_density_all.png")
for s in seasons:
    sdf = df[df['season'] == s]
    sdf['value'].plot.density(label=s, legend=True)
    plt.savefig("test_density_" + s + ".png")
    del ax.lines[-1]

在那里,我没有保存整体情节,而是在保存后删除季节线。问题在于它不会删除图例,因此虽然夏季图具有正确的两个密度,但它的图例包括四个项目(全部,冬季,春季,夏季)。

所以,我需要的是要么使上面的代码与图例一起工作,要么找到一种方法来存储整个图,以便我可以将它作为每个季节图的起点...

python pandas matplotlib plot
1个回答
1
投票

使用ax.legend()在情节中获得一个传奇。 请注意,这与使用legend=True参数不同,因为它根据绘图中当前显示的艺术家创建了一个新图例。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

n = 25
seasons = ['winter', 'spring', 'summer', 'autumn']
df = pd.DataFrame({'value': np.random.randn(n), 'season': np.random.choice(seasons, n)})

ax = df['value'].plot.density(label="all", legend=True)
plt.savefig("test_density_all.png")
for s in seasons:
    sdf = df[df['season'] == s]
    sdf['value'].plot.density(label=s)
    ax.legend()
    ax.figure.savefig("test_density_" + s + ".png")
    ax.lines[-1].remove()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.