使用数据值注释折线图

时间:2019-10-28 09:07:53

标签: python pandas matplotlib

我有多个折线图。我想在每行中绘制与熊猫数据框中的值相对应的数据值。但是,我在注释这些数据点时遇到了困难。

这是我为尝试解决此问题而编写的代码示例:

ax= weekdays.plot(marker='o',label='Conversion rates between signup states')
ax.set_xticklabels(['original','sunday','monday',
                 'tuesday','wednesday','thursday',
                 'friday','saturday'])
for i in weekdays.values:
    ax.text(str(i),xy=i)

这是我的数据示例(来自工作日数据框)。我将其作为字典返回以方便阅读:

{'filter': {0: 'original',
  1: 'sunday',
  2: 'monday',
  3: 'tuesday',
  4: 'wednesday',
  5: 'thursday',
  6: 'friday',
  7: 'saturday'},
 'session_to_leads': {0: 16.28,
  1: 13.88,
  2: 13.63,
  3: 15.110000000000001,
  4: 13.469999999999999,
  5: 13.54,
  6: 12.58,
  7: 12.82},
 'leads_to_opps': {0: 9.47,
  1: 6.279999999999999,
  2: 7.62,
  3: 8.6,
  4: 7.5600000000000005,
  5: 7.9,
  6: 7.08,
  7: 5.7299999999999995},
 'opps_to_complete': {0: 1.92,
  1: 0.86,
  2: 1.3599999999999999,
  3: 1.69,
  4: 1.3599999999999999,
  5: 1.48,
  6: 1.51,
  7: 0.88}}

1 个答案:

答案 0 :(得分:0)

您可以使用plotly以其他方式尝试它。您可以首先使用以下代码生成一个包含3列的新数据框,

values = weekdays.T.values[1:].ravel()
idx = weekdays.T.values[0].ravel().tolist() * 3 

cols = weekdays.columns[1:]
cols_ = []
for col in cols:
    cols_.append([col]*8)
cols_ = np.array(cols_).ravel()

weekdays_ = pd.DataFrame({'days': idx, 'values': values, 'cols': cols_})

,输出如下:

         days values              cols
0    original  16.28  session_to_leads
1      sunday  13.88  session_to_leads
2      monday  13.63  session_to_leads
3     tuesday  15.11  session_to_leads
4   wednesday  13.47  session_to_leads
5    thursday  13.54  session_to_leads
6      friday  12.58  session_to_leads
7    saturday  12.82  session_to_leads
8    original   9.47     leads_to_opps

现在,您可以使用以下内容来获取情节

import plotly_express as px # or import plotly.express as px

px.line(weekdays_, x='days', y='values', color='cols')

会产生以下互动情节。

interactive plotly chart