python-matplotlib-柱状堆积图

本文深入介绍了如何使用Matplotlib库创建柱状图,包括设置窗口大小、绘制单个柱状图和堆叠柱状图。通过实例展示了如何调整柱状图的细节,如颜色、填充图案、标签和图例,以及如何控制Y轴范围和刻度参数。此外,还讨论了柱状图在数据可视化中的应用。

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

matplot的画图,虽然好像很简单,但是又很搞人
bar官方文档

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
bar_data = pd.read_csv('data.csv', header=None)
plt.rcParams['font.family'] = "Times New Roman"
fig, ax = plt.subplots(figsize=(5, 3), dpi=200)

# 这里的数据是1行24列
x= np.linspace(0, 23, 24)
bar1= bar_data.iloc[0, 0:].values
bar2= bar_data.iloc[1, 0:].values
bar3= bar_data.iloc[2, 0:].values

width = .4

ax.bar(x, bar1, width, align='center', label='bar1',color='white',hatch="//",ec='k',lw=.6)
ax.bar(x, bar2, width,  bottom=bar1, label='bar2',color='gray',ec='k',lw=.6)
ax.bar(x, bar3, width,  bottom=bar1+ bar2, label='bar3',color='white',hatch="...",ec='k',lw=.6)


ax.set_ylim(0, 3)
ax.tick_params(direction='out', labelsize=12, length=5.5, width=1, top=False, right=False)
ax.legend(fontsize=11, frameon=False, loc='upper center', ncol=4)
ax.set_ylabel('Electricity Cost', fontsize=13)
ax.set_xlabel('Time Slot', fontsize=13)
text_font = {'size': '17', 'weight': 'bold', 'color': 'black'}
ax.text(.03, .93, "(a)", transform=ax.transAxes, fontdict=text_font, zorder=4)
ax.text(.87, -.08, '\nVisualization by DataCharm', transform=ax.transAxes,
        ha='center', va='center', fontsize=5, color='black', fontweight='bold', family='Roboto Mono')
plt.show()

1.窗口大小 figsize=(宽, 高), dpi=分辨率
尺寸单位:英寸(1 英寸=2.54 厘米),分辨率:每1英寸上的像素点数

plt.subplots(figsize=(5, 3), dpi=200)

2.绘制单个柱状图

ax.bar(x, bar1, width, align='center', label='bar1',color='white',hatch="//",ec='k',lw=.6)

x轴数据,
y轴数据,
宽度:取值在0~1之间,默认为0.8
排列:‘center’或者’edge’,居中或者左对齐
标签名
颜色
填充图案: {’/’, ‘’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’}
ec:设置填充图案的颜色
lw:设置填充图案的宽度

3.堆叠柱状图

ax.bar(x, bar2, width,  bottom=bar1, label='bar2',color='gray',ec='k',lw=.6)
ax.bar(x, bar3, width,  bottom=bar1+ bar2, label='bar3',color='white',hatch="...",ec='k',lw=.6)

bottom底部:关键是第三组要堆叠在第一组和第二组的和之上

4.效果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值