#基本设置
import numpy as np #加载numpy包
np.set_printoptions(precision=4) #设置numpy输出为4位有效数
from math import pi #调用math中的圆周率参数
x=np.linspace(0,4*pi,60);x #生成[0,2*pi]上30个等差数列
array([ 0. , 0.213 , 0.426 , 0.639 , 0.852 , 1.0649, 1.2779, 1.4909, 1.7039, 1.9169, 2.1299, 2.3429, 2.5559, 2.7689, 2.9819, 3.1948, 3.4078, 3.6208, 3.8338, 4.0468, 4.2598, 4.4728, 4.6858, 4.8988, 5.1117, 5.3247, 5.5377, 5.7507, 5.9637, 6.1767, 6.3897, 6.6027, 6.8157, 7.0286, 7.2416, 7.4546, 7.6676, 7.8806, 8.0936, 8.3066, 8.5196, 8.7326, 8.9456, 9.1585, 9.3715, 9.5845, 9.7975, 10.0105, 10.2235, 10.4365, 10.6495, 10.8625, 11.0754, 11.2884, 11.5014, 11.7144, 11.9274, 12.1404, 12.3534, 12.5664])
from numpy import sin,cos,log,exp #调用numpy中的初等函数
import matplotlib.pyplot as plt #加载matplotlib包的绘图函数
plt.plot(x,sin(x)); #正弦函数 y=sin(x)
plt.plot(x,cos(x)); #余弦函数 y=cos(x)
plt.plot(x,log(x+1)); #对数函数 y=log(x+1)
plt.plot(x,exp(x)); #指数函数 y=exp(x)
t=np.linspace(0,2*pi);
x=2*sin(t);y=3*cos(t);
plt.plot(x,y,c='red');
plt.axvline(x=0); plt.axhline(y=0);
plt.text(0.2,1,r'$\frac{x^2}{a^2}+\frac{y^2}{b^2}=1$',fontsize=15);
x=np.linspace(-4,4,20);
y=x**2; # y=x^2 抛物线
plt.scatter(x,y); #二维散点图
plt.scatter(x,y,s=8*y); #二维气泡图,s=8y
X, Y = np.meshgrid(x, x) #从坐标向量x,y中返回坐标矩阵
Z = np.sin(np.sqrt(X**2 + Y**2)) #Z=sin(sqrt(X^2+Y^2))
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
Axes3D(fig).scatter(X, Y, Z);
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
Axes3D(fig).plot_surface(X, Y, Z);
#!pip install seaborn
import seaborn as sns #加载seaborn包
#(1)读取绘图用数据
import pandas as pd
BSdata=pd.read_excel('DaPy_data.xlsx','BSdata');BSdata.head()
学号 | 性别 | 身高 | 体重 | 支出 | 开设 | 课程 | 软件 | |
---|---|---|---|---|---|---|---|---|
0 | 1510248008 | 女 | 167 | 71 | 46.0 | 不清楚 | 都未学过 | No |
1 | 1510229019 | 男 | 171 | 68 | 10.4 | 有必要 | 概率统计 | Matlab |
2 | 1512108019 | 女 | 175 | 73 | 21.0 | 有必要 | 统计方法 | SPSS |
3 | 1512332010 | 男 | 169 | 74 | 4.9 | 有必要 | 编程技术 | Excel |
4 | 1512331015 | 男 | 154 | 55 | 25.9 | 有必要 | 都学习过 | Python |
#(2)中文字体段时需设置字体
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']; #设置中文字体为'黑体'
plt.rc('axes', unicode_minus=False)
sns.boxplot(x=BSdata['身高']);
sns.boxplot(y=BSdata['身高']); #竖着放的箱线图,也就是将x换成y
# 分组绘制箱线图,分组因子是“性别”,在x轴不同位置绘制。
sns.boxplot(x='性别',y='身高',data=BSdata);
sns.violinplot(x='开设', y='支出', hue='性别', data=BSdata);
sns.stripplot(x='性别', y='身高', data=BSdata, jitter=True);
sns.stripplot(x='性别', y='身高', data=BSdata, jitter=False);
sns.barplot(x='性别', y='身高', data=BSdata); #不同性别身高均值标准差图
sns.countplot(x='开设', hue="课程", data=BSdata);
import warnings
warnings.filterwarnings("ignore") #忽略警告信息
sns.factorplot(x='性别',col="开设",col_wrap=3,data=BSdata,kind="count",size=2,aspect=1.5);
BSdata['身高'].hist();
sns.distplot(BSdata['身高'], kde=True, bins=10);
#针对双变量,可使用Seaborn中的jointplot()函数。
sns.jointplot(x='身高', y='体重', data=BSdata);
sns.pairplot(BSdata[['身高','体重','支出']]); #配对散点图
#!pip install ggplote #在系统上安装ggplot包
#!pip install plotnine #在系统上安装plotnine包
from plotnine import * #加载和调用ggplot所有方法
theme_set(theme_bw(base_family='SimHei'));
#设置图形主题背景为白色bw、中文字体为黑体SimHei
GP=ggplot(BSdata,aes(x='身高',y='体重')); GP #绘制直角坐标系
<ggplot: (175413053552)>
GP + geom_point() #增加点图
<ggplot: (175413053477)>
GP + geom_line() #增加线图
<ggplot: (175413179320)>
GP + geom_point() + geom_line() #增加点和线图
<ggplot: (175413140836)>
ggplot(BSdata,aes(x='身高')) + geom_histogram()
<ggplot: (175413143992)>
ggplot(BSdata,aes(x='身高',y='体重',shape='性别')) + geom_point()
<ggplot: (175413106719)>
ggplot(BSdata,aes(x='身高',y='体重',color='性别')) + geom_point()
<ggplot: (175413229686)>
ggplot(BSdata,aes(x='支出',y='身高')) + geom_line()
<ggplot: (175413412127)>
#共用一个坐标,绘制不同的y值
ggplot(BSdata,aes(x='支出'))+geom_line(aes(y='身高')) + geom_line(aes(y='体重'))
<ggplot: (175413068502)>
#在plotnine中可使用facet_wrap参数可以按类型绘制分面图。
ggplot(BSdata,aes('身高','体重')) + geom_point() + facet_wrap('性别',nrow=2)
<ggplot: (175413069921)>
ggplot(BSdata,aes('身高','体重')) + geom_point() + facet_wrap('性别',nrow=1)
<ggplot: (175413437784)>
ggplot(BSdata,aes('身高','体重')) + geom_line() + geom_point() + facet_wrap('开设',nrow=1)
<ggplot: (175413502434)>
(ggplot(BSdata,aes('身高','体重')) + geom_point()
+ facet_wrap('~性别+开设',nrow=3))
<ggplot: (175413441250)>
#!pip install pyecharts
#加载 Jupyter lab中设置 pyecharts 全局显示参数
from pyecharts.globals import CurrentConfig, NotebookType
CurrentConfig.NOTEBOOK_TYPE = NotebookType.JUPYTER_LAB
import pyecharts.options as opts #并加载pyecharts选项
figsize=opts.InitOpts(width='560px',height='380px',bg_color='white') #设置图形大小和背景色
from pyecharts.charts import Gauge
Gauge().load_javascript() #在Jupyterlab中制图前需加载一次JavaScript函数!!
#Gauge().add("",[("完成率", 66.6)]).render_notebook()
Gauge(figsize).add("",[("完成率", 90)]).render_notebook()
#基本的pyecharts绘图是基于列表数据的
X=['A','B','C','D','E','F','G']
Y=[1,4,7,3,2,5,6]
Z=[6,5,3,2,7,4,1]
from pyecharts.charts import Bar #加载pyecharts绘制条图(Bar)函数
bar1=Bar(figsize) #初始化条图
bar1.add_xaxis(X).add_yaxis("垂直条图",Y)
bar1.render_notebook()
Bar(figsize).add_xaxis(X).add_yaxis("",Y).render_notebook() #链式写法
bar2=Bar(figsize)
bar2.add_xaxis(X).add_yaxis("水平条图",Y).reversal_axis()
bar2.render_notebook()
bar3=Bar(figsize)
bar3.add_xaxis(X).add_yaxis("条1",Y).add_yaxis("条2",Z) #复试条图
bar3.render_notebook()
bar4=Bar(figsize)
bar4.add_xaxis(X) #分段条图
bar4.add_yaxis("条1",Y,stack="stack1")
bar4.add_yaxis("条2",Z,stack="stack1")
bar4.render_notebook()
XY = [list(z) for z in zip(X,Y)];XY #形成饼图数据列表格式
#XY.sort(key=lambda x: x[1]);XY #数据从小到大排序
[['A', 1], ['B', 4], ['C', 7], ['D', 3], ['E', 2], ['F', 5], ['G', 6]]
from pyecharts.charts import Pie #加载pyecharts绘制饼图(Pie)函数
Pie(figsize).add("饼图",XY).render_notebook()
(Pie(figsize)
.add("",XY)
.set_series_opts(opts.LabelOpts(formatter="{b}:{c}")) #加标签饼图
.render_notebook()
)
Pie(figsize).add("玫瑰饼图",XY,rosetype="radius").render_notebook()
Pie(figsize).add('圆圈图',XY,radius=['10%','75%']).render_notebook()
from pyecharts.charts import Funnel
fun1=Funnel(figsize)
fun1.add("漏斗图", XY)
fun1.render_notebook()
#Funnel(figsize).add("漏斗图", XY).render_notebook()
fun2=Funnel(figsize)
fun2.add("漏斗图", XY,label_opts=opts.LabelOpts(position="inside"))
fun2.render_notebook()
from pyecharts.charts import Line #加载pyecharts绘制线图(Line)函数
Line(figsize).add_xaxis(X).add_yaxis('线图',Y).render_notebook()
line2=Line(figsize)
line2.add_xaxis(X).add_yaxis("线1",Y).add_yaxis("线2",Z)
line2.render_notebook()
import pandas as pd
BS=pd.read_excel('DaPy_data.xlsx','BSdata'); #继续使用BSdata数据
BS.head()
学号 | 性别 | 身高 | 体重 | 支出 | 开设 | 课程 | 软件 | |
---|---|---|---|---|---|---|---|---|
0 | 1510248008 | 女 | 167 | 71 | 46.0 | 不清楚 | 都未学过 | No |
1 | 1510229019 | 男 | 171 | 68 | 10.4 | 有必要 | 概率统计 | Matlab |
2 | 1512108019 | 女 | 175 | 73 | 21.0 | 有必要 | 统计方法 | SPSS |
3 | 1512332010 | 男 | 169 | 74 | 4.9 | 有必要 | 编程技术 | Excel |
4 | 1512331015 | 男 | 154 | 55 | 25.9 | 有必要 | 都学习过 | Python |
from pyecharts.charts import Scatter
scatter1=Scatter(figsize)
scatter1.add_xaxis(BS.身高).add_yaxis("",BS.体重)
scatter1.render_notebook() #默认散点图的x轴和y轴从0开始
#修改x轴和y轴的刻度
scatter2=(Scatter(figsize)
.add_xaxis(BS.身高)
.add_yaxis("散点图",BS.体重,label_opts=opts.LabelOpts(is_show=False))
.set_global_opts(
xaxis_opts=opts.AxisOpts(min_=150), #x轴最小150
yaxis_opts=opts.AxisOpts(min_=40) #y轴最小40
)
)
scatter2.render_notebook()
#基本的pyecharts绘图是基于列表数据的, 通常需将数据框转换成列表
pt1=BS.pivot_table(index=['性别'],values=['学号'],aggfunc=len); pt1
学号 | |
---|---|
性别 | |
女 | 25 |
男 | 27 |
from pyecharts.charts import Bar
(Bar(figsize)
.add_xaxis(list(pt1.index))
.add_yaxis("性别统计图",list(pt1.学号))
.render_notebook()
)
pt2=BS.pivot_table(['学号'],['开设'],['性别'],aggfunc=len); pt2
学号 | ||
---|---|---|
性别 | 女 | 男 |
开设 | ||
不必要 | 6 | 5 |
不清楚 | 9 | 3 |
有必要 | 10 | 19 |
(Bar(figsize)
.add_xaxis(list(pt2.index))
.add_yaxis("女",list(pt2.学号.女))
.add_yaxis("男",list(pt2.学号.男))
.render_notebook()
)
import numpy as np
pt3=BS.pivot_table(["支出"],['开设'],aggfunc={np.mean,np.std});
pt3=pt3.round(2); pt3 #pt3['支出']['mean']
支出 | ||
---|---|---|
mean | std | |
开设 | ||
不必要 | 36.68 | 26.47 |
不清楚 | 26.29 | 20.87 |
有必要 | 19.16 | 18.06 |
(Bar(figsize)
.add_xaxis(list(pt3.index))
.add_yaxis("均值",list(pt3['支出']['mean'])) #list(pt3.iloc[:,0])
.add_yaxis("标准差",list(pt3['支出']['std']))
.render_notebook()
)