在 matplotlib 中向条形图和折线图添加标签值

sri*_*avi 0 python matplotlib

我为以下数据框创建了一个使用两个不同 y 轴的条形图和一个折线图在此处输入图片说明.

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]
 }) 
Run Code Online (Sandbox Code Playgroud)

使用以下代码,我还可以在条形图中每个条形旁边显示值。但是,到目前为止,我还没有成功尝试显示线图的标签(百分比)值。

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')
Run Code Online (Sandbox Code Playgroud)

# 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)                                                     
Run Code Online (Sandbox Code Playgroud)

add_value_labels(ax) plt.show()

有人可以建议如何在同一图中显示条形图和线图的标签吗?

She*_*ore 6

这是一个修改后的函数,它将实现所需的任务。诀窍是根据您拥有的图表类型提取 x 和 y 值。对于折线图,您可以使用ax.lines[0]然后get_xdataget_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')
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明