如何使用Pandas在Area图表上创建点和值?

时间:2016-11-14 11:14:09

标签: python pandas matplotlib

所以我正在尝试使用Jupyter笔记本为我的团队创建一个KPI工具,但我仍然坚持在Area图表上创建点和值。 代码:

df_all = pd.DataFrame(columns=['total_message_with_event','total_message','captured_ratio'], index = np.arange(5))
df_all.index = week_table
df_all.total_message = result[0]
df_all.total_message_with_event = result_with_event[0]
df_all.captured_ratio = ratio
df_graph = df_all[['total_message_with_event','total_message']]
df_graph = df_graph[::-1]
graph = df_graph.plot.area(title='Event Team Week-based Statistics', stacked = False)
box = graph.get_position()
graph.set_position([box.x0, box.y0, box.width, box.height*0.9])
graph.legend(df_all[['total_message_with_event','total_message']], loc='upper center', bbox_to_anchor=(0.728, 1.25))
graph.set_ylabel('Number of Messages')
graph.yaxis.set_tick_params(pad=2)
def millions(x, pos):
    'The two args are the value and tick position'
    return '%1.1fM' % (x*1e-6)
formatter = FuncFormatter(millions)
graph.yaxis.set_major_formatter(formatter)
df_all = df_all[::-1]
df_all

Current result

它应该看起来像这样,点和值在它们之上: Expected result

1 个答案:

答案 0 :(得分:0)

以下是一些可供使用的示例数据,因为您没有提供任何可用的数据:

Seq.map unpack

现在让我们通过在同一轴上绘制面积和折线图来创建图表:

np.random.seed(0)
df_graph = pd.DataFrame(data=np.transpose([np.random.rand(5)*1e7,np.random.rand(5)*1e6]),
                      columns=['total_message','total_message_with_event'],
                      index = ["Week {}".format(x) for x in range(40,45)])

Resulting chart

更新/旁注

这是一个使用plotly的解决方案:

fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(16,9))

colors = ['#3366CC', '#DC3912']
colors_light = ['#C2D1F0', '#CAA4AE']
# Plot an area chart
df_graph.plot.area(stacked = False, color=colors_light, ax=ax, alpha=0.5)
# Plot a line chart with dot markers on the same chart
df_graph.plot(ax=ax, marker='o', color=colors, legend=False)

ax.set_title(label='Event Team Week-based Statistics', size=18)

#box = graph.get_position()
#ax.set_position([box.x0, box.y0, box.width, box.height*0.9])
#ax.legend(df_all[['total_message_with_event','total_message']], loc='upper center', bbox_to_anchor=(0.728, 1.25))

ax.set_ylabel('Number of Messages')
ax.yaxis.set_tick_params(pad=2)

def millions(x, pos):
    'The two args are the value and tick position'
    return '%1.1fM' % (x*1e-6)
formatter = mpl.ticker.FuncFormatter(millions)
ax.yaxis.set_major_formatter(formatter)

for i, label in enumerate(list(df_graph.index)):
    # Annotate the first
    score = df_graph.ix[label, 'total_message_with_event']
    ax.annotate("{:,.0f}".format(score), (i, score), va='bottom',ha='center')
    # Annotate the second
    score = df_graph.ix[label, 'total_message']
    ax.annotate("{:,.0f}".format(score), (i, score), va='bottom',ha='center')

这为您提供了一个直接在Jupyter笔记本中的交互式图形,其中在悬停时它显示值:

enter image description here

您可以在线测试此图表here