Python-Matplotlib,将百分位数10,50、90的三个点显示在相同横坐标,不同纵坐标上
时间: 2024-04-30 21:17:18 浏览: 14
你可以使用Matplotlib库的percentile函数来计算百分位数,并将这些数值作为y轴坐标,同时将10、50和90作为x轴坐标。下面是一个示例代码:
```python
import numpy as np
import matplotlib.pyplot as plt
# 生成一些示例数据
data = np.random.normal(size=1000)
# 计算10、50、90百分位数
percentiles = np.percentile(data, [10, 50, 90])
# 绘制水平线
plt.axhline(y=percentiles[0], color='r', linestyle='-')
plt.axhline(y=percentiles[1], color='g', linestyle='-')
plt.axhline(y=percentiles[2], color='b', linestyle='-')
# 设置x轴坐标
plt.xticks([10, 50, 90], ['10%', '50%', '90%'])
# 绘制图形
plt.plot(data)
# 显示图形
plt.show()
```
这段代码会生成一个包含百分位数的Matplotlib图形,其中10%、50%、90%三个点分别显示在不同的y轴坐标上。你可以根据需要修改这些百分位数和坐标轴标签。
相关问题
Python-Matplotlib,纵轴显示百分位数10,50、90的三个点,横轴不显示任何数据
你可以使用Matplotlib库中的PercentFormatter和EmptyLocator类来实现这个需求。以下是一个示例代码:
```
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter, NullLocator
# 生成随机数据
data = np.random.normal(size=10000)
# 创建子图
fig, ax = plt.subplots()
# 绘制直方图
n, bins, patches = ax.hist(data, bins=50, density=True)
# 设定纵轴标签为百分位数
ax.yaxis.set_major_formatter(PercentFormatter(1.0))
# 禁止横轴刻度显示
ax.xaxis.set_major_locator(NullLocator())
# 绘制纵轴的10%、50%、90%三个点
quantiles = np.percentile(data, [10, 50, 90])
ax.plot(quantiles, [0.1, 0.5, 0.9], 'ro')
plt.show()
```
这段代码会生成一个直方图,并在纵轴下方显示三个红点,表示数据的10%、50%、90%分位数。横轴不会显示任何数据。
为什么python中matplotlib横坐标和纵坐标显示不了中文,只能显示数字?
默认情况下,matplotlib使用的字体不支持中文显示,因此在图表中显示中文会出现乱码或者无法显示的情况。为了显示中文,需要设置matplotlib使用支持中文的字体。
具体来说,可以按照以下步骤设置中文字体:
1. 导入matplotlib库和matplotlib字体管理器。
```python
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
```
2. 创建一个字体管理器对象,指定中文字体文件的路径。
```python
font = FontProperties(fname='中文字体文件的路径', size=字号)
```
其中,`中文字体文件的路径`是指中文字体文件在电脑上的路径,`字号`可以根据需要进行调整。
3. 在绘图时,使用字体管理器对象指定中文字体。
```python
plt.xlabel('横坐标', fontproperties=font)
plt.ylabel('纵坐标', fontproperties=font)
plt.title('标题', fontproperties=font)
```
这样,就可以在matplotlib中正确显示中文了。如果还不能正常显示中文,可以考虑更换其他中文字体文件。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)