In [10]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties # 修改字体
最简单的图表¶
In [3]:
x = [5,7,2,10]
plt.plot(x) ### 画折线图,传入一个值的话,这个值就是y轴值
plt.show()
In [5]:
x = [5,7,2,10]
y = [3,9,10,5]
plt.plot(x,y) ### 画折线图,传入两个值的话,第一个代表x值,第二个代表y值。
plt.show()
In [13]:
x = [1,3,6,9]
y = [12,5,10,20]
font=FontProperties(fname='C:\Windows\Fonts\simhei.ttf')
plt.figure(figsize=(10,6)) #### 设置画板大小,第一个值表示宽度,第二个值表示高度。
plt.title('两个参数的折线图',fontproperties=font, fontsize=20, color='red') ### 设置标题
plt.xlabel('x轴', fontproperties=font,fontsize=15, color='red') ### 设置 x轴的说明
plt.ylabel('y轴', fontproperties=font,fontsize=20, color='blue') ### 设置 y 轴的说明
plt.plot(x, y)
plt.show()
#### 存在的问题:1.中文乱码
解决方案一:修改配置文件¶
matplotlib 从配置文件 matplotlibrc 中读取配置,字体相关内容也在其中。查询当前matplotlibrc 所在目录,可以用 get_configdir()函数:
通常存放位置:lib\site-packages\matplotlib\mpl-data\matplotlibrc
In [ ]:
import matplotlib
matplotlib.get_configdir()
涉及到字体部分的设置内容为:
In [37]:
#font.family : sans-serif
#font.style : normal
#font.variant : normal
#font.weight : normal
#font.stretch : normal
## note that font.size controls default text sizes. To configure
## special text sizes tick labels, axes, labels, title, etc, see the rc
## settings for axes and ticks. Special text sizes can be defined
## relative to font.size, using the following values: xx-small, x-small,
## small, medium, large, x-large, xx-large, larger, or smaller
#font.size : 10.0
#font.serif : DejaVu Serif, Bitstream Vera Serif, Computer Modern Roman, New Century Schoolbook, Century Schoolbook L, Utopia, ITC Bookman, Bookman, Nimbus Roman No9 L, Times New Roman, Times, Palatino, Charter, serif
#font.sans-serif : DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
#font.cursive : Apple Chancery, Textile, Zapf Chancery, Sand, Script MT, Felipa, cursive
#font.fantasy : Comic Sans MS, Chicago, Charcoal, ImpactWestern, Humor Sans, xkcd, fantasy
#font.monospace : DejaVu Sans Mono, Bitstream Vera Sans Mono, Computer Modern Typewriter, Andale Mono, Nimbus Mono L, Courier New, Courier, Fixed, Terminal, monospace
matplotlib 默认使用的 font.family 是 sans-serif,即无衬线字体,可以看到在font.sans-serif中设置的全部为西文字体,这里的设置和css样式文件中设置差不多,只需要添加系统存在的字体名称即可(需要注意的是,matplotlib:
只支持ttf格式的字体),设置时需要将注释符号#去除。
解决方案二:重载配置文件¶
In [38]:
import matplotlib as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['font.serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题,或者转换负号为字符串
In [31]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
In [32]:
#### windows配置
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
In [33]:
x = [1,3,6,9]
y = [12,5,10,20]
plt.figure(figsize=(10,6)) #### 设置画板大小
plt.title('标题',fontsize=20, color='red') ### 设置标题
plt.xlabel('x轴',fontsize=15, color='blue') ### 设置 x轴的说明
plt.ylabel('y轴', fontsize=20, color='blue') ### 设置 y 轴的说明
plt.plot(x, y)
plt.show()
解决方案三:自定义字体¶
In [40]:
import numpy as np
import pylab as pl
import matplotlib.font_manager as fm
myfont = fm.FontProperties(fname=r'C:\Windows\Fonts\simhei.ttf') # 设置字体
t = np.arange(0.0,2.0 * np.pi,0.01) # 自变量取值范围
s = np.sin(t) # 计算正弦函数值
z = np.cos(t) # 计算余弦函数值
pl.plot(t,s,label='正弦')
pl.plot(t,z,label='余弦')
pl.xlabel('x-变量',fontproperties=myfont,fontsize=24) #设置标签
pl.ylabel('y-正弦余弦函数值',fontproperties=myfont,fontsize=24)
pl.title('sin-cos函数图像',fontproperties=myfont,fontsize=32) #图像标题
pl.legend(prop=myfont)
pl.show()
将电影产地和上映电影数量画成柱状图¶
In [20]:
import pandas as pd
movies = pd.read_csv('./douban_movie.csv') ### 只需要read_csv函数, 将csv中的所有数据读出
movies
Out[20]:
In [21]:
movies.groupby('产地').groups
Out[21]:
In [22]:
res = movies.groupby('产地').size().sort_values(ascending=False)
res
Out[22]:
In [12]:
res[0]
Out[12]:
In [23]:
res.values
Out[23]:
In [24]:
res.index
Out[24]:
统计每一年电影的数量的折线图¶
In [104]:
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties # 修改字体
font=FontProperties(fname='C:\Windows\Fonts\simfang.ttf')
plt.style.use('ggplot') # 设置条形图的背景
plt.figure(figsize=(18,6))
Product_origin=res.index
movies_count = res.values
plt.xlabel('产地',FontProperties=font,fontsize=15,color='blue')
plt.ylabel('出影数',FontProperties=font,fontsize=15,color='blue')
plt.title('产地-电影数量',FontProperties=font,fontsize=30)
plt.xticks(fontproperties=font, size=18, rotation=90) ### 对坐标轴上的刻度进行设置 rotation控制字体旋转
for a,b in zip(Product_origin,movies_count):
plt.text(a,b+100,b,ha='center') #### 参数1控制x轴文本,参数2控制柱上的数字,+100是柱子和数字之间的距离,参数3控制文本在柱子上居中,参数4控制字体大小
plt.bar(Product_origin,movies_count,color='darkgreen')
# plt.savefig('./a.png') #### 保存图片
plt.show()
统计每一年电影的数量的折线图¶
In [48]:
movies.groupby('年代').groups
Out[48]:
In [62]:
res = movies.groupby('年代').size().sort_index()[:-2] #### 按照年代分组,用size统计每年对应的数量,再以年代为索引排序,[:-2]删除最后两个无效数据
res
Out[62]:
In [64]:
x = res.index
y = res.values
plt.figure(figsize=(10,6))
plt.title('每年电影数量的折线图',FontProperties=font,color='red',size=20)
plt.xlabel('年代',FontProperties=font,color='blue',size=15)
plt.ylabel('数量',FontProperties=font,color='blue',size=15)
plt.plot(x,y)
plt.show()
根据电影时长 画出一个饼图分布¶
In [65]:
#### 分布的范围:0-70 70-100 100-130 130-----
In [66]:
t = pd.cut([10,5,20,15,8], (2,10,15,50)) ### 第一个参数是待分割的数据 第二个参数是分割的范围
t
Out[66]:
In [72]:
res = t.value_counts() ### 将值相同的进行分组并且计算个数
res
Out[72]:
In [73]:
res.index
Out[73]:
In [74]:
res.values
Out[74]:
In [76]:
movie_time = movies['时长']
movie_time
Out[76]:
In [79]:
res_time = pd.cut(movie_time,(0,70,100,130,1000)).value_counts()
res_time
Out[79]:
In [85]:
x = res_time.index
y = res_time.values
plt.figure(figsize=(10,6))
plt.title('电影时长分布图', FontProperties=font, color='red', size=20)
patchs, l_text, p_text = plt.pie(y,labels=x, autopct='%.2f%%')
for l in l_text: ### l_text 就是一个lable的列表
l.set_size(15)
l.set_color('red')
for p in p_text: #### p_text: 就是百分比值
p.set_size(15)
p.set_color('white')
plt.show()
matplotlib模块第二部分:matplotlib模块 07