(十三)Matplotlib知识学习5-python数据分析与机器学习实战(学习笔记)

文章原创,最近更新:2018-05-9

1.原数据的展示
2.折线图的细节设置
课程来源: python数据分析与机器学习实战-唐宇迪

为了方便学习,将练习所涉及的练习percent-bachelors-degrees-women-usa.csv文件以百度网盘共享的方式分享出来.
链接: https://pan.baidu.com/s/1igpIRU3g7rBkJm2nnkY6tg 密码: 8tsw

1.原数据的展示

percent-bachelors-degrees-women-usa.csv文件本数据集汇总了从1970年到2011年之间美国大学各专业中女生数占总学生数的百分比例数值,男女生共100人,如下图所示:

2.折线图的细节设置

利用Pandas库读入CSV文件,并快速绘制生物学专业女生比例随着年份变化的曲线图.

曲线图完整的代码如下;

import pandas as pd
import matplotlib.pyplot as plt

women_degrees=pd.read_csv('percent-bachelors-degrees-women-usa.csv')
plt.plot(women_degrees["Year"],women_degrees["Biology"])

plt.show()

输出的结果如下:


如何在同一子图中,绘制两条不同颜色的线性图,并且图例在左上方,有标题等相关元素?

完整的代码如下:

import pandas as pd
import matplotlib.pyplot as plt

women_degrees=pd.read_csv('percent-bachelors-degrees-women-usa.csv')

plt.plot(women_degrees['Year'], women_degrees['Biology'], c='blue', label='Women')
plt.plot(women_degrees['Year'], 100-women_degrees['Biology'], c='green', label='Men')
plt.legend(loc='upper right')
plt.title('Percentage of Biology Degrees Awarded By Gender')
plt.show()

输出的结果如下:

如何设置忽略x轴和y轴的刻度?

这里涉及到的知识点是.tick_params()函数
matplotlib.pyplot.tick_params(axis ='both',** kwargs )
作用是更改刻度线,刻度线标签和网格线的外观。

  • axis : {'x','y','both'},可选将参数应用于哪个轴。
    运行的轴; 默认axis=both表示同时影响x、y轴的刻度.
  • bottom, top, left, right : 布尔型.
    是否绘制相应的刻度。
    参考资料:matplotlib官方资料

可以利用子图ax对象的tick_params属性,忽略x轴和y轴的刻度

完整的代码如下:

import pandas as pd
import matplotlib.pyplot as plt

women_degrees=pd.read_csv('percent-bachelors-degrees-women-usa.csv')

fig,ax=plt.subplots()
ax.plot(women_degrees['Year'], women_degrees['Biology'], c='blue', label='Women')
ax.plot(women_degrees['Year'], 100-women_degrees['Biology'], c='green', label='Men')
ax.tick_params(bottom="off", top="off", left="off", right="off")
ax.legend(loc='upper right')
ax.set_title('Percentage of Biology Degrees Awarded By Gender')
ax.legend(loc="upper right")

plt.show()

输出的结果是:


如何设置忽略绘图显示的边框?

这里涉及到的函数是如下:
for key,spine in ax.spines.items():
spine.set_visible(False)
作用是隐藏坐标系的外围框线
注意:关于.spines.items()网上可以查的内容很少,这里也不是很理解.

利用子图中spine对象中的items属性,可以忽略绘图显示的边框,具体代码如下:

import pandas as pd
import matplotlib.pyplot as plt

women_degrees=pd.read_csv('percent-bachelors-degrees-women-usa.csv')

fig,ax=plt.subplots()
ax.plot(women_degrees['Year'], women_degrees['Biology'], c='blue', label='Women')
ax.plot(women_degrees['Year'], 100-women_degrees['Biology'], c='green', label='Men')
ax.tick_params(bottom="off", top="off", left="off", right="off")
ax.legend(loc='upper right')
ax.set_title('Percentage of Biology Degrees Awarded By Gender')

for key,spine in ax.spines.items():
    spine.set_visible(False)
ax.legend(loc="upper right")

plt.show()

输出的结果如下:


如何在同一画布中绘制4个子图,并且分别显示'Biology', 'Computer Science', 'Engineering', 'Math and Statistics'这四个专业的男女生比例随年份变化的趋势?

代码如下:

import pandas as pd
import matplotlib.pyplot as plt

women_degrees=pd.read_csv('percent-bachelors-degrees-women-usa.csv')
major_cats=['Biology', 'Computer Science', 'Engineering', 'Math and Statistics']
fig=plt.figure(figsize=(12,12))

for sp in range(0,4):
    ax=fig.add_subplot(2,2,sp+1)
    ax.plot(women_degrees['Year'], women_degrees[major_cats[sp]], c='blue', label='Women')
    ax.plot(women_degrees['Year'], 100-women_degrees[major_cats[sp]], c='green', label='Men')
plt.legend(loc="upper right")
plt.show()

输出的结果如下:


从以上输出的结果来看,不是很满意,想对绘图曲线取消边框/刻度,设置标题,并且重新设置xy轴的刻度标签,那又应该怎么操作呢?

代码如下:

import pandas as pd
import matplotlib.pyplot as plt

women_degrees=pd.read_csv('percent-bachelors-degrees-women-usa.csv')
major_cats=['Biology', 'Computer Science', 'Engineering', 'Math and Statistics']
fig=plt.figure(figsize=(12,12))

for sp in range(0,4):
    ax=fig.add_subplot(2,2,sp+1)
    ax.plot(women_degrees['Year'], women_degrees[major_cats[sp]], c='blue', label='Women')
    ax.plot(women_degrees['Year'], 100-women_degrees[major_cats[sp]], c='green', label='Men')
    for key,spine in ax.spines.items():
        spine.set_visible(False)
    ax.set_xlim(1968,2011)
    ax.set_ylim(0,100)
    ax.set_title(major_cats[sp])
    ax.tick_params(bottom="off", top="off", left="off", right="off")

plt.legend(loc="upper right")
plt.show()

输出的结果如下:


怎么用RGB更改折线的颜色

以下是比较通用的RGB颜色


其他的颜色的RGB颜色,可以在其他相关的网站寻找.

代码如下:


import pandas as pd
import matplotlib.pyplot as plt

women_degrees = pd.read_csv('percent-bachelors-degrees-women-usa.csv')
major_cats = ['Biology', 'Computer Science', 'Engineering', 'Math and Statistics']


cb_dark_blue = (0/255, 107/255, 164/255)
cb_orange = (255/255, 128/255, 14/255)

fig = plt.figure(figsize=(12, 12))

for sp in range(0,4):
    ax = fig.add_subplot(2,2,sp+1)
    # The color for each line is assigned here.
    ax.plot(women_degrees['Year'], women_degrees[major_cats[sp]], c=cb_dark_blue, label='Women')
    ax.plot(women_degrees['Year'], 100-women_degrees[major_cats[sp]], c=cb_orange, label='Men')
    for key,spine in ax.spines.items():
        spine.set_visible(False)
    ax.set_xlim(1968, 2011)
    ax.set_ylim(0,100)
    ax.set_title(major_cats[sp])
    ax.tick_params(bottom="off", top="off", left="off", right="off")

plt.legend(loc='upper right')
plt.show()

输出的结果如下:


从以上结果可以看到每个子图折线的宽度太窄,看起来有点不爽,有没有办法可以让子图看起来更清晰一些呢?

在ax.plot参数增加折线宽度的设置,设置linewidth=10
修改前:

ax.plot(women_degrees['Year'], women_degrees[major_cats[sp]], c=cb_dark_blue, label='Women')
ax.plot(women_degrees['Year'], 100-women_degrees[major_cats[sp]], c=cb_orange, label='Men')

修改后:

ax.plot(women_degrees['Year'], women_degrees[major_cats[sp]], c=cb_dark_blue, label='Women',linewidth=10)
ax.plot(women_degrees['Year'], 100-women_degrees[major_cats[sp]], c=cb_orange, label='Men',linewidth=10)

修改后完整的代码如下:

import pandas as pd
import matplotlib.pyplot as plt

women_degrees = pd.read_csv('percent-bachelors-degrees-women-usa.csv')
major_cats = ['Biology', 'Computer Science', 'Engineering', 'Math and Statistics']


cb_dark_blue = (0/255, 107/255, 164/255)
cb_orange = (255/255, 128/255, 14/255)

fig = plt.figure(figsize=(12, 12))

for sp in range(0,4):
    ax = fig.add_subplot(2,2,sp+1)
    ax.plot(women_degrees['Year'], women_degrees[major_cats[sp]], c=cb_dark_blue, label='Women', linewidth=10)
    ax.plot(women_degrees['Year'], 100-women_degrees[major_cats[sp]], c=cb_orange, label='Men', linewidth=10)
    for key,spine in ax.spines.items():
        spine.set_visible(False)
    ax.set_xlim(1968, 2011)
    ax.set_ylim(0,100)
    ax.set_title(major_cats[sp])
    ax.tick_params(bottom="off", top="off", left="off", right="off")

plt.legend(loc='upper right')
plt.show()

输出的结果如下:


从以上结果看,效果还不是很完善,能否增加2个专业,并且将绘制的子图并排排列?

对画布的大小进行重新设置

修改前:

major_cats = ['Biology', 'Computer Science', 'Engineering', 'Math and Statistics']
fig = plt.figure(figsize=(12, 12))
ax = fig.add_subplot(2,2,sp+1)
for sp in range(0,4):
ax.plot(women_degrees['Year'], women_degrees[major_cats[sp]], c=cb_dark_blue, label='Women', linewidth=10)
ax.plot(women_degrees['Year'], 100-women_degrees[major_cats[sp]], c=cb_orange, label='Men', linewidth=10)
ax = fig.add_subplot(2,2,sp+1)
ax.set_title(major_cats[sp])

修改后:

stem_cats = ['Engineering', 'Computer Science', 'Psychology', 'Biology', 'Physical Sciences', 'Math and Statistics']
fig = plt.figure(figsize=(18, 3))
for sp in range(0,6)
ax = fig.add_subplot(1,6,sp+1)
ax.plot(women_degrees['Year'], women_degrees[stem_cats[sp]], c=cb_dark_blue, label='Women', linewidth=10)
ax.plot(women_degrees['Year'], 100-women_degrees[stem_cats[sp]], c=cb_orange, label='Men', linewidth=10)
ax = fig.add_subplot(1,6,sp+1)
ax.set_title(stem_cats[sp])

修改后的代码如下:

import pandas as pd
import matplotlib.pyplot as plt

women_degrees = pd.read_csv('percent-bachelors-degrees-women-usa.csv')
stem_cats = ['Engineering', 'Computer Science', 'Psychology', 'Biology', 'Physical Sciences', 'Math and Statistics']


cb_dark_blue = (0/255, 107/255, 164/255)
cb_orange = (255/255, 128/255, 14/255)

fig = plt.figure(figsize=(18, 3))

for sp in range(0,6):
    ax = fig.add_subplot(1,6,sp+1)
    ax.plot(women_degrees['Year'], women_degrees[stem_cats[sp]], c=cb_dark_blue, label='Women', linewidth=10)
    ax.plot(women_degrees['Year'], 100-women_degrees[stem_cats[sp]], c=cb_orange, label='Men', linewidth=10)
    for key,spine in ax.spines.items():
        spine.set_visible(False)
    ax.set_xlim(1968, 2011)
    ax.set_ylim(0,100)
    ax.set_title(stem_cats[sp])
    ax.tick_params(bottom="off", top="off", left="off", right="off")

plt.legend(loc='upper right')
plt.show()

输出的结果如下:

怎么在第1张以及第6张子图的两条折线上添加文字?

.text()函数相关的知识:
例如ax.text(1, 2, "I'm a text")
前两个参数表示文本坐标, 第三个参数为要添加的文本

通过ax.text()进行设置,就可以在两条折线上添加文字.
完整的代码如下:

import pandas as pd
import matplotlib.pyplot as plt

women_degrees = pd.read_csv('percent-bachelors-degrees-women-usa.csv')
stem_cats = ['Engineering', 'Computer Science', 'Psychology', 'Biology', 'Physical Sciences', 'Math and Statistics']


cb_dark_blue = (0/255, 107/255, 164/255)
cb_orange = (255/255, 128/255, 14/255)

fig = plt.figure(figsize=(18, 3))

for sp in range(0,6):
    ax = fig.add_subplot(1,6,sp+1)
    ax.plot(women_degrees['Year'], women_degrees[stem_cats[sp]], c=cb_dark_blue, label='Women', linewidth=10)
    ax.plot(women_degrees['Year'], 100-women_degrees[stem_cats[sp]], c=cb_orange, label='Men', linewidth=10)
    for key,spine in ax.spines.items():
        spine.set_visible(False)
    ax.set_xlim(1968, 2011)
    ax.set_ylim(0,100)
    ax.set_title(stem_cats[sp])
    ax.tick_params(bottom="off", top="off", left="off", right="off")
    if sp ==0:
        ax.text(2005,87,'Men')
        ax.text(2002, 8, 'Women')
    elif sp==5:
        ax.text(2005, 62, 'Men')
        ax.text(2001, 35, 'Women')

plt.show()

输出的结果如下:


你可能感兴趣的:((十三)Matplotlib知识学习5-python数据分析与机器学习实战(学习笔记))