python 绘制并列条形图并添加数据标签

本文介绍如何使用Python绘制并列的条形图,并通过具体实例展示了从数据读取到图表绘制及优化的全过程。文章首先利用pandas库加载Excel文件中的数据,接着运用matplotlib库的plt.bar函数绘制了两组并列的条形图,最后通过添加数据标签对图表进行了美化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

利用python绘制并列的条形图。
(1)处理数据,计算每个区间的个数:
在这里插入图片描述

(2)plt.bar函数绘制条形图:

df = pd.read_excel('path of file ',sheet_name='Sheet1')

area_class = df['name']

lake_num = df['lake_number']

TP_lake_num = df['TP_2020_lake_number']

bar_width = 0.3  

index_lake = np.arange(len(area_class))

index_TP = index_lake + bar_width

plt.bar(index_lake, height=lake_num, width=bar_width, color='b', label='study_2020_lake')

plt.bar(index_TP, height=TP_lake_num, width=bar_width, color='g', label='TP_2020_lake')

plt.legend() 

plt.xticks(index_lake + bar_width/2, area_class)  

plt.ylabel('Number') 

plt.xlabel('Area (km$^{2}$)') 

plt.show()

显示结果:
在这里插入图片描述
(3)图形优化
为每个柱添加数据标签:

df = pd.read_excel('path of file',sheet_name='Sheet1')

fig, ax = plt.subplots()

area_class = df['name']

lake_num = df['lake_number']

TP_lake_num = df['TP_2020_lake_number']

bar_width = 0.3  

index_lake = np.arange(len(area_class))

index_TP = index_lake + bar_width

plt.bar(index_lake, height=lake_num, width=bar_width, color='b', label='study_lake')

for x, y in enumerate(df['lake_number'].values):
    
    # plt.text(x, y+1,y,ha='center', va='bottom')
    
    plt.text(x+0.1, y+1,y,ha='right',va='bottom')
    
plt.bar(index_TP, height=TP_lake_num, width=bar_width, color='g', label='TP_lake')

for a, b in enumerate(df['TP_2020_lake_number'].values):
    
    plt.text(a+0.1, b+1,b,ha='left',va='bottom')
    
plt.legend() 

plt.xticks(index_lake + bar_width/2, area_class)  

plt.ylabel('Number') 

plt.xlabel('Area (km$^{2}$)') 

plt.show()

显示结果:
在这里插入图片描述
plt.text()函数参数说明:https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.text.html

### 使用Python绘制并列条形图 为了创建并列条形图,可以利用`seaborn`库中的`barplot()`函数来实现这一目标。此函数允许指定不同的分类变量作为分组依据,通过设置参数`hue`来进行进一步细分[^1]。 ```python import seaborn as sns import matplotlib.pyplot as plt sns.set(style="darkgrid") fig, ax = plt.subplots(figsize=(8, 6)) # 绘制并列条形图 colors = ["#69b3a2", "#4374B3"] sns.barplot(x="day", y="total_bill", hue="smoker", data=df, errorbar=None, palette=colors) plt.title('Total Bill by Day and Smoking Status') plt.xlabel('Day of Week') plt.ylabel('Total Bill ($)') plt.legend(title='Smoker') plt.show() ``` 上述代码片段展示了如何基于给定的数据集`df`,按照星期几(`day`)以及是否吸烟者(`smoker`)两个维度来构建并列条形图。这里设置了图表的颜色方案、尺寸大小及标题等内容以增强可读性。 对于更复杂的场景,如果希望在同一张图中展示更多层次的信息,则可以通过组合多个绘图命令或将数据划分为不同子图的方式来完成: ```python # 分组/子分组条形图 g = sns.catplot( x="sex", y="total_bill", hue="smoker", col="day", data=df, kind="bar", height=4, aspect=.7 ) for ax in g.axes.flat: ax.set_xticklabels(ax.get_xticklabels(), rotation=45) plt.show() ``` 这段代码不仅实现了基本的并列条形图功能,而且还引入了额外的一级分类——性别(`sex`),通过多面板布局分别呈现每一天的情况。这有助于更加直观地比较各因素之间的差异。 #### 解决中文乱码问题 当涉及到含有汉字字符的情况下,可能遇到字体渲染方面的问题。为此,在绘图之前应当配置合适的字体以便正确显示中文文字[^5]。 ```python import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False # 正常显示负号 ``` 通过以上设置,可以在后续生成的所有图形中正常显示出简体中文标签和其他文本元素。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值