matplotlib 的几种柱状图

本文详细介绍了使用Matplotlib进行数据可视化的三种常见场景:单一数据集的水平条形图、多重组合的柱状图以及多重组合的折线图。通过具体代码示例,读者可以学习如何设置图表样式、调整布局、添加中文标签以及保存高分辨率的图片。

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

1、x 表示数量,y 表示名字

 1 import matplotlib.pyplot as plt
 2 
 3 
 4 dic = {'a': 22, 'b': 10, 'c': 6, 'd': 4, 'e': 2, 'f': 10, 'g': 24, 'h': 16, 'i': 1, 'j': 12}
 5 s = sorted(dic.items(), key=lambda x: x[1], reverse=False)  # 对dict 按照value排序 True表示翻转 ,转为了列表形式
 6 print(s)
 7 x_x = []
 8 y_y = []
 9 for i in s:
10     x_x.append(i[0])
11     y_y.append(i[1])
12 
13 x = x_x
14 y = y_y
15 
16 fig, ax = plt.subplots()
17 ax.barh(x, y, color="deepskyblue")
18 labels = ax.get_xticklabels()
19 plt.setp(labels, rotation=0, horizontalalignment='right')
20 
21 for a, b in zip(x, y):
22     plt.text(b+1, a, b, ha='center', va='center')
23 ax.legend(["label"],loc="lower right")
24 
25 plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
26 plt.ylabel('name')
27 plt.xlabel('数量')
28 plt.rcParams['savefig.dpi'] = 300  # 图片像素
29 plt.rcParams['figure.dpi'] = 300  # 分辨率
30 plt.rcParams['figure.figsize'] = (15.0, 8.0)  # 尺寸
31 plt.title("title")
32 
33 plt.savefig('D:\\result.png')
34 plt.show()

2、x 表示名字,y 表示数量,多重组合

import matplotlib.pyplot as plt
import numpy as np

x = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
y1 = [6, 5, 8, 5, 6, 6, 8, 9, 8, 10]
y2 = [5, 3, 6, 4, 3, 4, 7, 4, 4, 6]
y3 = [4, 1, 2, 1, 2, 1, 6, 2, 3, 2]

plt.bar(x, y1, label="label1", color='red')
plt.bar(x, y2, label="label2",color='orange')
plt.bar(x, y3, label="label3", color='lightgreen')

plt.xticks(np.arange(len(x)), x, rotation=0, fontsize=10)  # 数量多可以采用270度,数量少可以采用340度,得到更好的视图
plt.legend(loc="upper left")  # 防止label和图像重合显示不出来
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.ylabel('数量')
plt.xlabel('name')
plt.rcParams['savefig.dpi'] = 300  # 图片像素
plt.rcParams['figure.dpi'] = 300  # 分辨率
plt.rcParams['figure.figsize'] = (15.0, 8.0)  # 尺寸
plt.title("title")
plt.savefig('D:\\result.png')
plt.show()

3、x为线路,y 为值,多重组合

import matplotlib.pyplot as plt
import numpy as np

size = 10
y1 = [6, 5, 8, 5, 6, 6, 8, 9, 8, 10]
y2 = [5, 3, 6, 4, 3, 4, 7, 4, 4, 6]
y3 = [4, 1, 2, 1, 2, 1, 6, 2, 3, 2]

x = np.arange(size)
total_width, n = 0.8, 3     # 有多少个类型,只需更改n即可
width = total_width / n
x = x - (total_width - width) / 2

plt.bar(x, y1,  width=width, label='label1',color='red')
plt.bar(x + width, y2, width=width, label='label2',color='deepskyblue')
plt.bar(x + 2 * width, y3, width=width, label='label3', color='green')

plt.xticks()
plt.legend(loc="upper left")  # 防止label和图像重合显示不出来
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.ylabel('value')
plt.xlabel('line')
plt.rcParams['savefig.dpi'] = 300  # 图片像素
plt.rcParams['figure.dpi'] = 300  # 分辨率
plt.rcParams['figure.figsize'] = (15.0, 8.0)  # 尺寸
plt.title("title")
plt.savefig('D:\\result.png')
plt.show()

 

转载于:https://www.cnblogs.com/BackingStar/p/10986955.html

### Matplotlib直方图不显示的原因分析与解决方案 当遇到 `Matplotlib` 的直方图无法正常显示的情况时,通常可能是由于以下几个原因引起的: #### 1. 数据格式问题 如果数据中存在缺失值或非数值类型的元素(如 `NaN` 或字符串),可能会导致直方图无法正确渲染。可以通过预处理数据来解决此问题[^1]。 ```python import numpy as np import matplotlib.pyplot as plt # 假设原始数据中有 NaN 值 data = [1, 2, 3, np.nan, 5] # 使用 NumPy 进行过滤 filtered_data = data[~np.isnan(data)] plt.hist(filtered_data, bins=10) plt.show() ``` #### 2. 绘制函数调用错误 在某些情况下,可能是因为未正确调用 `hist()` 函数而导致的异常。例如,传递给 `hist()` 的参数不符合其预期输入格式[^4]。 ```python # 正确的方式 plt.hist(data, bins='auto', alpha=0.7) # 错误方式可能导致崩溃 plt.hist([data], bins='auto') # 额外嵌套列表会引发问题 ``` #### 3. 图形窗口管理器冲突 有时,在特定的操作系统环境下运行脚本时,可能出现图形界面未能弹出的现象。这通常是由于后台绘图引擎设置不当所致。可以尝试更改默认的 backend 设置为支持交互模式的一种[^2]。 ```python import matplotlib matplotlib.use('TkAgg') # 更改为 Tkinter 后端 import matplotlib.pyplot as plt plt.figure() plt.hist(np.random.randn(100), bins=20) plt.show() # 应该能够看到窗口打开并展示图表 ``` #### 4. 对数尺度下的特殊行为 对于需要绘制对数坐标系上的直方图而言,需特别注意负值或者零值的存在会影响最终效果[^5]。 ```python values = np.abs(np.random.normal(loc=0., scale=.8, size=(1000))) logbins = np.logspace(np.log10(values.min()), np.log10(values.max()), num=50) plt.hist(values, bins=logbins) plt.xscale('log') plt.show() ``` 通过以上几种方法调整代码逻辑之后再重新测试应该能有效改善原问题中的 “直方图看起来很糟糕” 的状况。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值