微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

有效管理多条折线图45条独特的线

如何解决有效管理多条折线图45条独特的线

我的groupby挑战我试图用线图可视化10年中非洲国家的粮食生产(根据我的数据,为45)。使用groupby函数并取消堆叠后,绘图效果很好,但不可读,并且区分每条线的颜色很差。通过我的讲师的可视化,他使用了Wolfram。

如何使用Python来实现这一目标?或者我的方法还有更好的选择吗?

这是我的代码

#To make the legend readable we reduce the font size
from matplotlib.font_manager import FontProperties
fontP = FontProperties()
fontP.set_size('small')
fig,ax = plt.subplots(figsize = (20,16))


df1.groupby(['Year','Country',]).sum().unstack().plot(ax = ax)
ax.set_yscale("log")
ax.set_ylim(1,300000)

plt.ylabel('Year')
plt.xlabel('Total Value')
plt.title('Food Production in Africa over the Years')
plt.legend(title='Countries',bBox_to_anchor=(1.05,1),loc='upper left',prop=fontP)

我的讲师使用Wolfram的可视化

enter image description here

我的尝试

enter image description here

解决方法

由于没有可用的数据,我根据最新数据伪创建了非洲每个国家的人口趋势,然后使用ax.text(x,y,country)创建了数据。您的数据并不是那么拥挤,所以我认为这是适用的。该示例是根据the official reference定制的。

import pandas as pd
import numpy as np

df = pd.read_csv('./africa_t.csv',sep=',')

enter image description here

import matplotlib.pyplot as plt

fig,ax = plt.subplots(1,1,figsize=(12,14))

# These are the colors that will be used in the plot
ax.set_prop_cycle(color=[
    '#1f77b4','#aec7e8','#ff7f0e','#ffbb78','#2ca02c','#98df8a','#d62728','#ff9896','#9467bd','#c5b0d5','#8c564b','#c49c94','#e377c2','#f7b6d2','#7f7f7f','#c7c7c7','#bcbd22','#dbdb8d','#17becf','#9edae5'])

ax.spines['top'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)

ax.get_xaxis().tick_bottom()
ax.get_yaxis().tick_left()

fig.subplots_adjust(left=.06,right=.75,bottom=.02,top=.94)

ax.set_xticks(range(2011,2020,10))
ax.set_yticks(range(5000,210000000,5000000))
ax.xaxis.set_major_formatter('{x:.0f}')

ax.grid(True,'major','y',ls='--',lw=.5,c='k',alpha=.3)

ax.tick_params(axis='both',which='both',labelsize=14,bottom=False,top=False,labelbottom=True,left=False,right=False,labelleft=True)

country = df.columns

for column in country:
    line,= ax.plot(df['Year'].to_list(),df[column].to_list(),lw=2.5)
    y_pos = df[column].to_list()[-1] - 0.5
    ax.text(2020.5,y_pos,column,fontsize=14,color=line.get_color())

plt.show()

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。