python - 注释一些线图观察
问题描述
我创建了一个脚本,它在 53 周的单个折线图数据点中显示 3 条线。图表有效,标签显示,但人满为患。有谁知道如何枚举注释/数据标签,所以只有偶数周显示数据标签?以下是我的问题:
import pandas as pd
import matplotlib.pyplot as plt
CA_plot_df = CA_Data.pivot_table('ED Arrivals', ['W'], 'Year').reset_index()
CA_plot_df = CA_plot_df[1:-1]
df_2021 = CA_plot_df[['W',2021]].dropna()[:-1]
plt.style.use('ggplot')
plt.rcParams['axes.facecolor'] = 'white'
fig = plt.figure(figsize = (15,8))
ax = fig.add_subplot(111)
plt.plot(CA_plot_df.W, CA_plot_df[2019], label = 'year 2019', color = '#407c38', linewidth = 2)
for i,j in zip(CA_plot_df.W,CA_plot_df[2019]):
ax.annotate('%s' %round(j), xy=(i,j), xytext=(-2,5), textcoords='offset points')
plt.plot(CA_plot_df.W, CA_plot_df[2020], label = 'year 2020', color = '#b3b3b3', linewidth = 2)
plt.plot(df_2021.W, df_2021[2021], label = 'year 2021',color = '#d64550', linewidth = 2)
for i,j in zip(df_2021.W,df_2021[2021]):
ax.annotate('%s' %round(j), xy=(i,j), xytext=(-2,5), textcoords='offset points')
解决方案
- 最简单的选择可能是在添加注释时添加条件。
- 在以下情况下,仅在枚举值为偶数时添加注解。
for e, i, j in enumerate(zip(CA_plot_df.W, CA_plot_df[2019])):
if e%2 == 0:
ax.annotate('%s' %round(j), xy=(i,j), xytext=(-2,5), textcoords='offset points')
for e, i, j in enumerate(zip(df_2021.W, df_2021[2021])):
if e%2 == 0:
ax.annotate('%s' %round(j), xy=(i,j), xytext=(-2,5), textcoords='offset points')
工作示例
- 测试
pandas 1.3.0
和matplotlib 3.4.2
import pandas as pd
import seaborn as sns # for data only
# sample data; top 50 rows
df = sns.load_dataset('tips').loc[:50, ['total_bill', 'tip']]
# add plots
ax = df.plot(y='total_bill', marker='.', xlabel='Records', ylabel='Amount ($)', figsize=(15, 8))
df.plot(y='tip', marker='.', ax=ax)
# adds every other annotation
for e, (i, j) in enumerate(df[['total_bill']].iterrows()):
if e%2 == 0:
ax.annotate(f'{j.values[0]:0.1f}', xy=(i, j), xytext=(-2, 5), textcoords='offset points')
# adds every annotation
for e, (i, j) in enumerate(df[['tip']].iterrows()):
ax.annotate(f'{j.values[0]:0.1f}', xy=(i, j), xytext=(-2, 5), textcoords='offset points')
推荐阅读
- javascript - 如何通过反应中兄弟组件上的单击事件将图像加载到另一个组件中
- python - 在第二个轴上选择 Numpy
- java - 我怎样才能做一个慢循环?
- java - FirebaseMessagingService onMessageReceived 方法未在后台调用 DATA 有效负载
- sql - 是/否 查询列的格式
- python-3.x - ExcelLibrary - 机器人框架骑行 - 导入问题
- php - 尝试访问 null 类型值的数组偏移量(flashpub)
- json - 在颤动中显示来自 JSON 的选定值
- ios - 无法将应用上传到 App Store 连接
- python - 如何解决 PyCharm 中的 tensorflow 问题?