返回顶部

mataplotlib篇(开篇)

今日内容概要

  • matplotlib画各种图形
  • 数据操作补充
  • 数据清洗
  • 网络爬虫

今日内容详细

matplotlib画各种图形

# 首先导入模块
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

x = [2,5,7,10,11]
y = [1,2,3,4,5]
# 图形的名称
plt.title('title',fontsize=25,color='r') # title默认不支持中文 写的话会出现乱码
# 参数fontsize用来控制字体的大小
# 参数color用来控制字体的颜色 可以用英文全称也可以用首字母缩写(但是得注意首字母相同的情况)

# 给x轴加标签
plt.xlabel('x',fontsize=20,color='y')
# 给y轴加标签
plt.ylabel('y',fontsize=20,color='pink')
"""
只要是设置字体那么都可以使用
fontsize
color
"""
plt.plot(x,y)
plt.show()

中午展示配置

# 针对默认的中文不支持乱码的情况 需要进行下列配置
# 针对windows
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# 针对mac
# 配置
from matplotlib.font_manager import FontProperties
font = FontProperties(fname='/Users/jason/Downloads/font/Hanzipen.ttc',size=20)
font2 = FontProperties(fname='/Users/jason/Downloads/font/Hanzipen.ttc',size=13)
# 字体的选择可以有多个文件类型
# 使用
plt.title('这是一个图表',fontsize=25,color='r')
plt.xlabel('嗯',fontsize=20,color='y')
plt.ylabel('哼',fontsize=20,color='pink')
# 还可以控制图形展示大小、
plt.figure(figsize=(10,6)) # 单位为厘米

# 修改节点形状,先颜色
plt.plot(x,y,color='red',marker='o') # 形状可以查看具体用法

# 线型
plt.plot(x,y,linestyle = '--') # 默认是实线 可以变为虚线
         
"""
折线图plot配置
plt.plot([0,3,5,7,9,15,30],linestyle = '-',color='r',marker = 'o')
"""         

图形标注

title
xlabel
ylabel
xlim
    xlim(起始坐标,终止坐标)
ylim
    ylim(起始坐标,终止坐标)同xlim
    # xlim和ylim使用的并不是很多
xticks
      plt.xticks([1,1.5,2,2.5,3,3.5,4,4.5,5])
yticks
      plt.yticks([1,1.5,2,2.5,3,3.5,4,4.5,5])
    # xticks和yticks使用的非常的多 用于自定义轴刻度
legond
    曲线图例
         给每条线做备注

数字函数

a = np.arange(-100,100)
y1 = a
y2 = a ** 2
y3 = np.sin(a)
plt.plot(a,y1,label="y=a")  # lable是给对应的图形加标注
plt.plot(a,y2,label="y=a^2")
plt.plot(a,y3,label="y=sin(a)")
plt.ylim(-100,100)
plt.legend() # label在legend函数之后就会显示出来

画图思路

1.先获取数据

2.处理数据

3.获取画图必备的轴数据

4.先粗略的画出图形

5.之后再完善(不要一步到位)

图形名字

plot
    折线图
bar
    柱状图
    

柱状图

"""
zip函数的使用
C:\Users\Administrator>python
Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 23 2018, 23:31:17) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> l1 = [111,222,333,444,555,666]
>>> l2 = ['a','b','c','d','e','f']
>>> zip(l1,l2)
<zip object at 0x02F9BD00>
>>> list(zip(l1,l2))
[(111, 'a'), (222, 'b'), (333, 'c'), (444, 'd'), (555, 'e'), (666, 'f')]
"""
# 1.绘制每个国家或地区的电影数量柱状图(以豆瓣电影数据表为基础)
cf = pd.read_csv(r'C:\\douban_movie.csv')
cf
运行结果:
名字	投票人数	类型	产地	上映时间	时长	年代	评分	首映地点
0	肖申克的救赎	692795.0	剧情/犯罪	美国	1994-09-10 00:00:00	142.0	1994	9.6	多伦多电影节
1	控方证人	42995.0	剧情/悬疑/犯罪	美国	1957-12-17 00:00:00	116.0	1957	9.5	美国
2	美丽人生	327855.0	剧情/喜剧/爱情	意大利	1997-12-20 00:00:00	116.0	1997	9.5	意大利
3	阿甘正传	580897.0	剧情/爱情	美国	1994-06-23 00:00:00	142.0	1994	9.4	洛杉矶首映
4	霸王别姬	478523.0	剧情/爱情/同性	中国大陆	1993-01-01 00:00:00	171.0	1993	9.4	香港
...	...	...	...	...	...	...	...	...	...
38730	神学院 S	46.0	Adult	法国	1905-06-05 00:00:00	58.0	1983	8.6	美国
38731	1935年	57.0	喜剧/歌舞	美国	1935-03-15 00:00:00	98.0	1935	7.6	美国
38732	血溅画屏	95.0	剧情/悬疑/犯罪/武侠/古装	中国大陆	1905-06-08 00:00:00	91.0	1986	7.1	美国
38733	魔窟中的幻想	51.0	惊悚/恐怖/儿童	中国大陆	1905-06-08 00:00:00	78.0	1986	8.0	美国
38734	列宁格勒围困之星火战役 Блокада: Фильм 2: Ленинградский ме...	32.0	剧情/战争	苏联	1905-05-30 00:00:00	97.0	1977	6.6	美国
38735 rows × 9 columns

# 按照产地(国家)列分组并求电影数量
res = cf.groupby('产地').size()
res
运行结果:
产地
USA       113
中国台湾      618
中国大陆     3802
中国香港     2852
丹麦        198
俄罗斯       221
其他       1920
加拿大       723
印度        357
墨西哥       119
巴西        101
德国        902
意大利       749
日本       5053
比利时       139
法国       2817
波兰        181
泰国        294
澳大利亚      300
瑞典        193
美国      11866
苏联        256
英国       2762
荷兰        155
西德        130
西班牙       447
阿根廷       116
韩国       1351
dtype: int64
    
# 再对电影数量进行排序
res = res.sort_values(ascending=False)
res
运行结果:
产地
美国      11866
日本       5053
中国大陆     3802
中国香港     2852
法国       2817
英国       2762
其他       1920
韩国       1351
德国        902
意大利       749
加拿大       723
中国台湾      618
西班牙       447
印度        357
澳大利亚      300
泰国        294
苏联        256
俄罗斯       221
丹麦        198
瑞典        193
波兰        181
荷兰        155
比利时       139
西德        130
墨西哥       119
阿根廷       116
USA       113
巴西        101
dtype: int64

# 获取x轴坐标
x = res.index(这里的x轴坐标用的是标签index(产地))
x
运行结果:
Index(['美国', '日本', '中国大陆', '中国香港', '法国', '英国', '其他', '韩国', '德国', '意大利', '加拿大',
       '中国台湾', '西班牙', '印度', '澳大利亚', '泰国', '苏联', '俄罗斯', '丹麦', '瑞典', '波兰', '荷兰',
       '比利时', '西德', '墨西哥', '阿根廷', 'USA', '巴西'],
      dtype='object', name='产地')
# 获取y轴坐标
y = res.values(这里的y轴坐标取的是值value(标签对应的电影数量))
y
运行结果:
array([11866,  5053,  3802,  2852,  2817,  2762,  1920,  1351,   902,
         749,   723,   618,   447,   357,   300,   294,   256,   221,
         198,   193,   181,   155,   139,   130,   119,   116,   113,
         101], dtype=int64)
# 图像的优化操作
  1.x轴长度
    plt.figure(figsize=(20,6))
  2.x轴刻度大小及角度变化  
    plt.xticks(rotation=45,fontsize=15)
  3.设置图像标题
    plt.title('各国或地区的电影量',fontsize=30,color='b')
  4.设置x轴及y轴标签
    plt.xlabel('国家',fontsize=20)
	plt.ylabel('数量',fontsize=20)
  5.y轴刻度大小及角度变化
    plt.yticks(fontsize=20,rotation=45)
  6.在每个柱状图上方加上具体的数据(******)
   #思路:必须先获取到添加数字位置的坐标
    for a,b in zip(x,y):
   plt.text(a,b+100,b,horizontalalignment='center',fontsize=15)
 # text(x坐标,y坐标,写的内容,horizontalalignment='center'居中,verticalalignment='center'居中)
   
plt.bar(x,y)
plt.savefig('这就是你想要的图表吗')
plt.show()
7.导出图像
plt.savefig('这就是你想要的图表吗') # 切记将这条代码放在展现统计图"plt.show()"前面,否则导出来的图表将是一张空白的新图表(因为在 plt.show() 后调用了 plt.savefig() ,在 plt.show() 后实际上已经创建了一个新的空白的图片(坐标轴),这时候你再 plt.savefig() 就会保存这个新生成的空白图片。)

针对ipython环境

"""
补充:在ipython模块中
1.如果想在内部执行外部的pip安装命令 只需要加一个感叹号前缀即可
  !pip3 install numpy
  !pip3 install pandas
  !pip3 install matplotlib
2.生成的图片面板会自动含有多功能按钮
       多功能面板相同代码情况下只会出现一次
 """
 以例题1中的表格为例,运行结果如下:
  C:\Users\Administrator>ipython
Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 23 2018, 23:31:17) [MSC v.1916 32 bit (Intel)]
Type 'copyright', 'credits' or 'license' for more information
IPython 7.16.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import numpy as np

In [2]: import pandas as pd

In [3]: import matplotlib.pyplot as plt

In [4]: x = [2,5,7,10,11]^M
   ...: y = [1,2,3,4,5]^M
   ...: plt.title('这是一个图表',fontsize=25,color='r')^M
   ...: plt.xlabel('嗯',fontsize=20,color='y')^M
   ...: plt.ylabel('哼',fontsize=20,color='pink')^M
   ...: plt.plot(x,y)^M
   ...: plt.figure(figsize=(10,6))^M
   ...: plt.plot(x,y,color='red',marker='o',linestyle='-.')^M
   ...: plt.xticks([1,1.5,2,2.5,3,3.5,4,4.5,5])^M
   ...: plt.show()
c:\users\administrator\appdata\local\programs\python\python36-32\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 36825 missing from current font.
  font.set_text(s, 0.0, flags=flags)
c:\users\administrator\appdata\local\programs\python\python36-32\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 26159 missing from current font.
  font.set_text(s, 0.0, flags=flags)
c:\users\administrator\appdata\local\programs\python\python36-32\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 19968 missing from current font.
  font.set_text(s, 0.0, flags=flags)
c:\users\administrator\appdata\local\programs\python\python36-32\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 20010 missing from current font.
  font.set_text(s, 0.0, flags=flags)
c:\users\administrator\appdata\local\programs\python\python36-32\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 22270 missing from current font.
  font.set_text(s, 0.0, flags=flags)
c:\users\administrator\appdata\local\programs\python\python36-32\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 34920 missing from current font.
  font.set_text(s, 0.0, flags=flags)
c:\users\administrator\appdata\local\programs\python\python36-32\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 21999 missing from current font.
  font.set_text(s, 0.0, flags=flags)
c:\users\administrator\appdata\local\programs\python\python36-32\lib\site-packages\matplotlib\backends\backend_agg.py:201: RuntimeWarning: Glyph 21999 missing from current font.
  font.set_text(s, 0, flags=flags)
c:\users\administrator\appdata\local\programs\python\python36-32\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 21756 missing from current font.
  font.set_text(s, 0.0, flags=flags)
c:\users\administrator\appdata\local\programs\python\python36-32\lib\site-packages\matplotlib\backends\backend_agg.py:201: RuntimeWarning: Glyph 21756 missing from current font.
  font.set_text(s, 0, flags=flags)
c:\users\administrator\appdata\local\programs\python\python36-32\lib\site-packages\matplotlib\backends\backend_agg.py:201: RuntimeWarning: Glyph 36825 missing from current font.
  font.set_text(s, 0, flags=flags)
c:\users\administrator\appdata\local\programs\python\python36-32\lib\site-packages\matplotlib\backends\backend_agg.py:201: RuntimeWarning: Glyph 26159 missing from current font.
  font.set_text(s, 0, flags=flags)
c:\users\administrator\appdata\local\programs\python\python36-32\lib\site-packages\matplotlib\backends\backend_agg.py:201: RuntimeWarning: Glyph 19968 missing from current font.
  font.set_text(s, 0, flags=flags)
c:\users\administrator\appdata\local\programs\python\python36-32\lib\site-packages\matplotlib\backends\backend_agg.py:201: RuntimeWarning: Glyph 20010 missing from current font.
  font.set_text(s, 0, flags=flags)
c:\users\administrator\appdata\local\programs\python\python36-32\lib\site-packages\matplotlib\backends\backend_agg.py:201: RuntimeWarning: Glyph 22270 missing from current font.
  font.set_text(s, 0, flags=flags)
c:\users\administrator\appdata\local\programs\python\python36-32\lib\site-packages\matplotlib\backends\backend_agg.py:201: RuntimeWarning: Glyph 34920 missing from current font.
  font.set_text(s, 0, flags=flags)    
posted @ 2020-09-08 15:11  Satan—yuan  阅读(407)  评论(1编辑  收藏  举报