import pandas as pd
df = pd.DataFrame({
'DXC':['T1', 'H1', 'HP', 'T1_or_H1_or_HP'],
'Count': [2485, 5595, 3091, 9933],
'percent':[1.06, 2.39, 1.31, 4.23]
})
使用以下代码,我还可以在条形图中的每个条形旁边显示值。但是,到目前为止,我还没有成功显示线图的标签(百分比)值。
fig=plt.figure()
#AX: bar chart
ax=df["Count"].plot(kind="bar", color="orange")
ax.set_ylabel("Counts")
ax.set_xlabel("")
ax.set_ylim(0,20000)
for tick in ax.get_xticklabels():
tick.set_rotation(0)
#AX2: Create secondary y-axis with same x-axis as above for plotting percent values
ax2=ax.twinx()
ax2.plot(ax.get_xticks(),df["percent"], color="red", linewidth=4, marker = "o")
ax2.grid(False)
ax2.set_ylabel("Percent", color = "red")
ax2.set_ylim(0,4.5)
ax2.tick_params(labelcolor="red", axis='y')
# Function to add value labels to bar chart
def add_value_labels(ax, spacing=5):
for i in ax.patches:
y_value = i.get_height()
x_value = i.get_x() + i.get_width() / 2
space = spacing
va = 'bottom'
# Use Y value as label and format number with no decimal place
label = "{:.0f}".format(y_value)
# Create annotation
ax.annotate(label,(x_value, y_value), xytext=(0, space), textcoords="offset points",
ha='center', va=va)
add_value_labels(ax)
plt.show()
有人可以建议如何在同一图中同时显示条形图和线形图的标签吗?
答案 0 :(得分:2)
这是修改后的功能,可以完成所需的任务。诀窍是根据您拥有的图表类型提取x和y值。对于折线图,可以使用ax.lines[0]
,然后使用get_xdata
和get_ydata
def add_value_labels(ax, typ, spacing=5):
space = spacing
va = 'bottom'
if typ == 'bar':
for i in ax.patches:
y_value = i.get_height()
x_value = i.get_x() + i.get_width() / 2
label = "{:.0f}".format(y_value)
ax.annotate(label,(x_value, y_value), xytext=(0, space),
textcoords="offset points", ha='center', va=va)
if typ == 'line':
line = ax.lines[0]
for x_value, y_value in zip(line.get_xdata(), line.get_ydata()):
label = "{:.2f}".format(y_value)
ax.annotate(label,(x_value, y_value), xytext=(0, space),
textcoords="offset points", ha='center', va=va)
add_value_labels(ax, typ='bar')
add_value_labels(ax2, typ='line')