import pandas as pd import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties font = FontProperties(fname=r"C:\Windows\Fonts\simhei.ttf", size=14) plt.rcParams["font.sans-serif"] = ["simhei"] # 读取Excel数据 df = pd.read_excel('people.xlsx') # 绘制柱状图 plt.bar(df['年末总人口'], df['指标']) plt.xlabel('年末总人口') plt.ylabel('指标') plt.title('年末总人口') plt.show()
时间: 2024-04-21 07:28:27 浏览: 11
这段代码的作用是读取名为 "people.xlsx" 的 Excel 文件中的数据,并使用 matplotlib 库绘制柱状图。具体步骤如下:
1. 导入 pandas、matplotlib.pyplot 和 matplotlib.font_manager 这三个库,分别用于读取 Excel 数据、绘制图形和管理字体。
2. 指定字体文件路径和字体大小,以便在图形中显示中文。
3. 使用 pandas 库的 read_excel() 函数读取 Excel 文件中的数据,并将其存储在名为 df 的数据框中。
4. 使用 matplotlib.pyplot 库的 bar() 函数绘制柱状图,其中 df['年末总人口'] 作为 x 轴,df['指标'] 作为 y 轴。
5. 使用 xlabel()、ylabel() 和 title() 函数设置图形的标签和标题。
6. 最后使用 show() 函数将图形显示出来。
需要注意的是,代码中指定的 simhei.ttf 字体文件路径可能需要根据具体的操作系统和字体安装路径进行修改。
相关问题
import pandas as pd import matplotlib.pyplot as plt # 读取Excel1和Excel2的数据 df1 = pd.read_excel('C:\\Users\\ASUS\\Desktop\\2023310道旅.xlsx') df2 = pd.read_excel('C:\\Users\\ASUS\\Desktop\\2023310危险品.xlsx') # 绘制箱型图 fig, ax = plt.subplots() ax.boxplot([df1['道旅报警数/百公里'], df2['危险品报警数/百公里']]) ax.set_xticklabels(['道路旅客', '危险品']) ax.set_ylabel('安全态势') plt.show()对这段代码修改字体
可以使用前面提到的方法之一,比如修改字体。以下是修改字体的代码:
```python
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
# 读取Excel1和Excel2的数据
df1 = pd.read_excel('C:\\Users\\ASUS\\Desktop\\2023310道旅.xlsx')
df2 = pd.read_excel('C:\\Users\\ASUS\\Desktop\\2023310危险品.xlsx')
# 绘制箱型图
fig, ax = plt.subplots()
font = FontProperties(fname=r"C:\Windows\Fonts\simhei.ttf", size=14)
ax.boxplot([df1['道旅报警数/百公里'], df2['危险品报警数/百公里']], labels=['道路旅客', '危险品'], fontproperties=font)
ax.set_ylabel('安全态势', fontproperties=font)
plt.show()
```
其中,`FontProperties` 指定了字体文件路径和大小,`labels` 参数直接指定标签,`set_ylabel` 方法也指定了字体。这里仍然使用了宋体字体 `simhei.ttf`,你可以根据需要修改。
在使用matplotlib.font_manager绘图时如何将数据源(csv表)里面的gb2312编码的中文正确地显示出来
在使用matplotlib绘图时,如果要正确显示中文,需要先设置字体。可以通过以下代码设置字体:
```python
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
# 设置字体
font = FontProperties(fname=r"C:\Windows\Fonts\simhei.ttf", size=14)
# 绘图
plt.plot(x, y)
plt.xlabel('日期', fontproperties=font)
plt.ylabel('销售额', fontproperties=font)
plt.title('销售额变化', fontproperties=font)
plt.show()
```
其中,`fname`参数指定字体文件路径,`size`参数指定字体大小。在Windows系统下,常见的中文字体文件为`simhei.ttf`、`simsun.ttc`等。
如果数据源中的中文编码格式为`gb2312`,需要在读取数据时指定编码格式,例如:
```python
import pandas as pd
df = pd.read_csv('data.csv', encoding='gb2312')
```
然后再将中文作为参数传递给绘图函数,并使用`fontproperties`参数指定字体即可正确显示中文。