【问题标题】:Labels at the end of curves (matplotlib-seaborn) [duplicate]曲线末端的标签(matplotlib-seaborn)[重复]
【发布时间】:2018-10-29 17:53:06
【问题描述】:

我有多个这种格式的数据框:

year    count   cum_sum
2001    5   5
2002    15  20
2003    14  34
2004    21  55
2005    44  99
2006    37  136
2007    55  191
2008    69  260
2009    133 393
2010    94  487
2011    133 620
2012    141 761
2013    206 967
2014    243 1210
2015    336 1546
2016    278 1824
2017    285 2109
2018    178 2287

我生成了如下图: enter image description here

以下代码已用于此目的:

fig, ax = plt.subplots(figsize=(12,8))

sns.pointplot(x="year", y="cum_sum", data=china_papers_by_year_sorted, color='red')
sns.pointplot(x="year", y="cum_sum", data=usa_papers_by_year_sorted, color='blue')
sns.pointplot(x="year", y="cum_sum", data=korea_papers_by_year_sorted, color='lightblue')
sns.pointplot(x="year", y="cum_sum", data=japan_papers_by_year_sorted, color='yellow')
sns.pointplot(x="year", y="cum_sum", data=brazil_papers_by_year_sorted, color='green')

ax.set_ylim([0,2000])
ax.set_ylabel("Cumulative frequency")

fig.text(x = 0.91, y = 0.76, s = "China", color = "red", weight = "bold") #Here I have had to indicate manually x and y coordinates
fig.text(x = 0.91, y = 0.72, s = "South Korea", color = "lightblue", weight = "bold") #Here I have had to indicate manually x and y coordinates

plt.show()

问题是在绘图中添加文本的方法无法识别数据坐标。因此,我不得不手动指示每个数据框标签的坐标(请参阅“中国”和“韩国”)。有没有聪明的方法呢?我看过一个使用“.last_valid_index()”方法的例子。但是,由于无法识别数据坐标,因此无法正常工作。

【问题讨论】:

  • 您可以使用重新缩放的数据坐标。只需将最后一个 y 值除以最大 y 值即可。这将为您提供重新缩放的坐标
  • 我想将其关闭为重复项是有意义的。 @Fernando 如果您在为您的案例实施链接解决方案时遇到问题,那么就具体问题提出一个新问题是有意义的,其中包含该问题的minimal reproducible example

标签: python matplotlib seaborn


【解决方案1】:

您无需重复调用pointplot 并手动添加标签。而是在您的数据框中添加一个country 列以指示国家/地区,组合数据框,然后使用国家/地区作为hue 简单地绘制累积总和与年份。

相反,请执行以下操作:

# Add a country label to dataframe itself
china_papers_by_year_sorted['country'] = 'China'
usa_papers_by_year_sorted['country'] = 'USA'
korea_papers_by_year_sorted['country'] = 'Korea'
japan_papers_by_year_sorted['country'] = 'Japan'
brazil_papers_by_year_sorted['country'] = 'Brazil'

# List of dataframes with same columns
frames = [china_papers_by_year_sorted, usa_papers_by_year_sorted,
          korea_papers_by_year_sorted, japan_papers_by_year_sorted,
          brazil_papers_by_year_sorted]

# Combine into one dataframe
result = pd.concat(frames)

# Plot.. hue will make country name a label
ax = sns.pointplot(x="year", y="cum_sum", hue="country", data=result)
ax.set_ylim([0,2000])
ax.set_ylabel("Cumulative frequency")
plt.show()

编辑:编辑添加如果您想注释行本身而不是使用图例,this existing question 的答案指示如何注释行尾。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-13
    • 2017-09-22
    • 2021-08-03
    • 2017-05-23
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多