python 我的传说怎么了,一些自然灾害的传说消失了?

ykejflvf  于 2023-01-16  发布在  Python
关注(0)|答案(2)|浏览(99)

我有这个代码:

import pandas as pd
df = pd.read_csv(r'C:\Users\ASUS\Downloads\number-of-natural-disaster-events.csv')
df.drop(['Code'], axis = 1)
df_pivot = df.pivot(index='Year',columns='Entity',values='Number of reported natural disasters (reported disasters)')
df_pivot = df_pivot.drop(['Impact'],axis=1)
df_pivot = df_pivot.fillna(0)
df_pivot = df_pivot.reset_index()
df_pivot
fig, ax = plt.subplots(1, 1, sharey=True, sharex=True, figsize=(20, 10))
legend = []
for col in df_pivot.columns:
    if col != "Year":
       sns.regplot(ax=ax,data=df_pivot,x="Year", y=col)
       legend.append(col)
       ax.legend(legend,bbox_to_anchor=(0.5, -0.1),fancybox=True,loc='upper center',shadow=True,
                   ncol=2)

CSV文件可用here
当我尝试代码时,我得到了这样的图表:

为什么图例输出错误?我试图使图例所有的自然灾害,以其各自的颜色线,但给圆圈代替。

有趣的是,如果我把regplot改为lineeplot,它会工作,所以我不确定是什么问题,因为我真的想使用seaborn.regplot

1qczuiv0

1qczuiv01#

如果您从sns中获取线条颜色,并使用Line2D将其添加到图例中,则可以正常工作。

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.lines as mlines
df = pd.read_csv(r'C:\Users\ASUS\Downloads\number-of-natural-disaster-events.csv')
df.drop(['Code'], axis = 1)
df_pivot = df.pivot(index='Year',columns='Entity',values='Number of reported natural disasters (reported disasters)')
df_pivot = df_pivot.drop(['Impact'],axis=1)
df_pivot = df_pivot.fillna(0)
df_pivot = df_pivot.reset_index()
df_pivot
fig, ax = plt.subplots(1, 1, sharey=True, sharex=True, figsize=(20, 10))
legend = []
for col in df_pivot.columns:
    if col != "Year":
        sns_ax = sns.regplot(ax=ax,data=df_pivot,x="Year", y=col)
        color = sns_ax.lines[-1].get_color()
        line = mlines.Line2D([], [],color = color, linewidth = 7,
                          markersize=15, label=col)
        legend.append(line)

ax.legend(handles=legend,bbox_to_anchor=(0.5, -0.1),fancybox=True,loc='upper center',shadow=True,ncol=2)
idfiyjo8

idfiyjo82#

你可以给线关键字添加一个标签,使线自动出现在图例中,代码也可以简化一点,而不需要重置索引并使用x=作为索引。
下面的代码使用seaborn的flights数据集以便于重现:

from matplotlib import pyplot as plt
import seaborn as sns

df = sns.load_dataset('flights')
df_pivot = df.pivot(index='year', columns='month', values='passengers')
df_pivot = df_pivot[['Mar', 'Jun', 'Sep', 'Dec']] # take only 4 months for a simpler example
df_pivot = df_pivot.fillna(0)

fig, ax = plt.subplots(figsize=(12, 7))
for col in df_pivot.columns:
    sns.regplot(ax=ax, data=df_pivot, x=df_pivot.index, y=col, line_kws={'label': col})

ax.legend(bbox_to_anchor=(0.5, -0.1), fancybox=True, loc='upper center', shadow=True, ncol=2)
plt.tight_layout()
plt.show()

如果你同时需要线和标记,你可以为每个regplot添加两个标签,使用ax.get_legend_handles_labels()你可以获取所有的andle和标签放入图例中,然后将它们组合成元组。

fig, ax = plt.subplots(figsize=(12, 7))
for col in df_pivot.columns:
    sns.regplot(ax=ax, data=df_pivot, x=df_pivot.index, y=col, label=col, line_kws={'label': col})
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles=[(h1, h2) for h1, h2 in zip(handles[::2], handles[1::2])],
          labels=labels[::2],
          bbox_to_anchor=(0.5, -0.1), fancybox=True, loc='upper center', shadow=True, ncol=2)

相关问题