如何使用plt排序x轴并获取条形标签

0 投票
1 回答
35 浏览
提问于 2025-04-12 20:12

我正在使用子图来绘制三个数据框,如下所示:

np.random.seed(0)
df1 = pd.DataFrame({'id' : np.random.choice(['a', 'b', 'c', 'd', 'e'], size = 20),
                   'score' : np.random.normal(size = 20)})
df1['score'] = np.abs(df1['score'])
df2 = pd.DataFrame({'id' : np.random.choice(['a', 'b', 'c', 'd', 'e'], size = 20),
                   'score' : np.random.normal(size = 20)})
df2['score'] = np.abs(df2['score'])
df3 = pd.DataFrame({'id' : np.random.choice(['a', 'b', 'c', 'd', 'e'], size = 20),
                   'score' : np.random.normal(size = 20)})
df3['score'] = np.abs(df3['score'])

我得到的结果是:

这里输入图片描述

有人能告诉我怎么把x轴的顺序从 ae 排好,并在柱子上显示数值标签吗?

1 个回答

1

试试这个脚本:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from matplotlib.axes._axes import Axes

np.random.seed(0)
df1 = pd.DataFrame({'id': np.random.choice(['a', 'b', 'c', 'd', 'e'], size=20), 'score': np.random.normal(size=20)})
df1['score'] = np.abs(df1['score'])
df2 = pd.DataFrame({'id': np.random.choice(['a', 'b', 'c', 'd', 'e'], size=20), 'score': np.random.normal(size=20)})
df2['score'] = np.abs(df2['score'])
df3 = pd.DataFrame({'id': np.random.choice(['a', 'b', 'c', 'd', 'e'], size=20), 'score': np.random.normal(size=20)})
df3['score'] = np.abs(df3['score'])

# Create a figure and a set of subplots
fig, axs = plt.subplots(1, 3, figsize=(15, 5))

def plot_df(ax: Axes, df: pd.DataFrame, title: str) -> None:
    """
    Plot a DataFrame as a bar chart on a given matplotlib Axes without annotations.

    Parameters:
    - ax (Axes): The matplotlib Axes object where the chart will be plotted.
    - df (pd.DataFrame): The DataFrame containing the data to plot. 
                         It must have columns 'id' and 'score'.
    - title (str): The title for the subplot.

    Returns:
    None
    """
    # Sort by 'id' column for ordered plotting
    df_sorted = df.sort_values(by='id')
    ax.bar(df_sorted['id'], df_sorted['score'])

    ax.set_title(title)
    ax.set_xlabel('ID')
    ax.set_ylabel('Score')
    # Ensure the x-axis has fixed categories
    ax.set_xticks(['a', 'b', 'c', 'd', 'e'])

# Plot each DataFrame
plot_df(axs[0], df1, 'DataFrame 1')
plot_df(axs[1], df2, 'DataFrame 2')
plot_df(axs[2], df3, 'DataFrame 3')

plt.tight_layout()
plt.show()

撰写回答