如何将值放置在条形图上(一些垂直,一些水平)?

问题描述 投票:0回答:1

我有什么 我想要什么

我希望将值插入到条上,并且应该相应地调整它们,以便它们看起来清晰。 (有些应该是垂直的,有些应该是水平的)

x2 = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC']
y3 = []
for value in x2:
    y3.append((df[value].sum())/(len(df[value])))

plt.bar(x2,y3,color=('lightblue','salmon'))

for i,v in enumerate(y3):
    plt.text(i-.25,v+1,str(v),fontsize=6)

plt.show()
python matplotlib bar-chart data-analysis
1个回答
0
投票

考虑下面的布局,这与@rehaqds的建议类似。

enter image description here

您还可以选择删除一些标签,例如较小的值 - 请参阅this问题。

可重现的示例

许多参数是可选的(如颜色、字体大小等),但我将它们包括在内是为了揭示如何轻松地根据自己的喜好调整布局。

#Imports
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# Data for testing
months = pd.date_range(start='Jan 2024', end='Dec 2024', freq='MS')
month_names = months.strftime('%b').tolist()

rainfall = np.array([2, 3, 4, 5, 7, 14, 25, 21, 14, 7, 4, 2]) * 10 + np.random.randn(12) * 2
mean_rainfall = rainfall.mean()

#
#Plot
#

#Create ax to plot on
f, ax = plt.subplots(figsize=(7, 3), layout='tight')

#Bar plot
bars = ax.bar(month_names, rainfall, color='lightblue', edgecolor='black', linewidth=0.5)

#Label the bars using bar_label
ax.bar_label(
    bars,
    rotation=45, label_type='edge', padding=2,
    fontsize=8, fontweight='bold', color='tab:blue', 
    fmt='{:.0f}'
)

#Mean
ax.axhline(mean_rainfall, linestyle=':', lw=1, color='darkred', label='mean rainfall')
ax.legend()

#Formatting
ax.set(xlabel='Month', ylabel='Rainfall (mm)', title='Average Monthly Rainfall\n')
ax.spines[['top', 'right']].set_visible(False)
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.