简体   繁体   English

为多个图表重新使用轴对象

[英]Re-using an axes object for several charts

I have a pandas DataFrame with values and an indicator for season. 我有一个带有值的pandas DataFrame和一个季节指示器。 I want to create a density plot for the whole set and then one for each season, which should include the overall density plus the season's density. 我想为整个场景创建一个密度图,然后为每个季节创建一个密度图,其中应包括总体密度加上季节的密度。
Since the overall density estimation takes some time (I have over 40000 data points), I want to avoid repeating it for each season. 由于总体密度估算需要一些时间(我有超过40000个数据点),因此我想避免每个季节重复进行估算。

So far, the closest I got is this code, based on 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]

There, instead of saving the overall plot, I am deleting the season-line after save. 在这里,我要保存的是删除季节线,而不是保存整个情节。 The problem is that it does not delete the legend, so while the summer-plot has the correct two densities, its legend includes four items (all, winter, spring, summer). 问题在于它不会删除图例,因此夏季图具有正确的两个密度时,其图例包括四个项目(全部,冬季,春季,夏季)。

So, what I need is either to make the above code work with legend, or to find a way to store the overall plot in such a way that I can use it as a start point for each of the season-plots... 因此,我需要的是使以上代码与图例一起使用,或者找到一种方式来存储整体图,以便我可以将其用作每个季节图的起点...

Use ax.legend() to get a legend in the plot. 使用ax.legend()获取图中的图例。
Note that this is different from using the legend=True argument, because it creates a new legend based on the currently present artists in the plot. 请注意,这与使用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()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM