我试图从比较政治数据集中按年份绘制人口和国家数据。前任:
year country pop15_64
1960 Australia 6296.50
1961 Australia 6428.60
1962 Australia 6571.50
1960 USA 107919.4
1961 USA 109048.6
1962 USA 111177.3
问题在于试图查看哪条线对应于哪个国家/地区。我尝试了许多不同的方法,最容易区分的似乎是将线条绘制为破折号。Ex(片段,不完整):
df2.loc[df2['country'] == 'Cyprus'].plot(x='year', y='pop15_64', ax=ax, color='k')
df2.loc[df2['country'] == 'Czech Republic'].plot(x='year', y='pop15_64', ax=ax, color='g', dashes=[3, 3])
但以上并不稳健。添加到数据集需要硬编码另一行,删除一个国家也是如此。这在数据上稳健地循环:
fig, ax = plt.subplots()
plt.xlabel('Year')
plt.ylabel('Population')
for countries in df2['country'].unique():
df2[df2['country']==countries].plot.line(x='year',
y='pop15_64',
ax=ax,
label=countries,
title='Country Population by Year')
ax.legend(handlelength=5)
plt.show()
...但我认为没有办法在不破坏循环的情况下自定义这些循环中的行。例如,这个:
for countries, x in df2['country'].unique():
df2[df2['country']==countries].plot.line(x='year',
y='pop15_64',
ax=ax,
dashes=[x+2, x],
label=countries,
title='Country Population by Year')
...results in a "ValueError: too many values to unpack (expected 2)"
What else I tried:
.groupby - couldn't get groupby and iterables to work together in one plot
iterables - had difficulty getting unique countries without losing the underlying data, still had line customization issues.
I admit that while I have experience in C, C++, and C#, I am a novice at python and more so with pandas. It requires a restructuring in how one thinks about problems. As a result, applying the many vaguely similar StackOverflow Q&A about custom lines and legends has not resulted in solutions like it might for someone with more experience. I hope someone knows an answer, and that this might help more than just me.
更新:在 Peter Leimbigler 的回答之后,我针对这个暂定解决方案修改了上述内容:
for i, countries in enumerate(df2['country'].unique()):
df2[df2['country']==countries].plot.line(x='year',
y='pop15_64',
ax=ax,
dashes=[3+i, i/2, abs(i-2), i/2],
label=countries)
我建议对您在循环中更改破折号属性的尝试进行以下更改:
for i, countries in enumerate(df2['country'].unique()):
这将需要进一步的风格调整,但应该是一个很好的起点。
更广泛地说,为了回应 Quang Hoang 的评论,很难在一个情节中呈现这么多行而不会有视觉混乱。两种可能的解决方法:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句