我正在使用子图绘制 3 个数据框,如下所示:
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 轴从
a
到 e
排序并获取栏上的值标签。
尝试这个脚本:
import pandas as pd
import numpy as np
from matplotlib.axes._axes import Axes
from typing import Any
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.
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')
bars = ax.bar(df_sorted['id'], df_sorted['score'])
# Add value on top of each bar
for bar in bars:
height = bar.get_height()
ax.annotate(f'{height:.2f}',
xy=(bar.get_x() + bar.get_width() / 2, height),
xytext=(0, 3), # 3 points vertical offset
textcoords="offset points",
ha='center', va='bottom')
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()