python处理数据与数据可视化

《python可matplotlib 实践》笔记||完善统计图形

2020-04-30  本文已影响0人  周运来就是我

在之前的笔记中,我们能用matplotlib绘出基本的统计图形了,但是有些细节如何修改呢?也许我们要首先知道的是什么叫细节:字体,大小,颜色,图例,布局。

在这一节我们会了解matplotlib 自带的TeX功能来达到发表级的文档主题。关于TeX的更多介绍可以看这一篇有LaTeX的深厚底蕴,Markdown是果然最美的编辑语言!!

好了,让我们开始搬砖吧。

matplotlib 主题设置:

import matplotlib.pyplot as plt
from matplotlib import cm as cm 
import numpy as  np
import matplotlib as mpl


mpl.rcParams["font.sans-serif"] = ["SimHei"]
mpl.rcParams["axes.unicode_minus"] = False

图例

x = np.linspace(-2*np.pi,2*np.pi,200)
y = np.sin(x)
y1 = np.cos(x)

plt.plot(x,y,label = r"$\sin(x)$")
plt.plot(x,y1,label = r"$\cos(x)$")
plt.legend(loc = "lower left")
plt.title("sin")
plt.show()

子图布局

plt.subplot(121)
plt.plot(x,y1,label = r"$\sin(x)$")

plt.subplot(122)
plt.xlim(-2*np.pi,2*np.pi)
plt.xticks([-2*np.pi,-3*np.pi/2,-1*np.pi,-1*np.pi/2,0,np.pi/2,np.pi,3*np.pi/2,1*np.pi],
           [r"$-2\pi$",r"$-3\pi/2$",r"$-\pi$",r"$-\pi/2$",r"$0$",r"$\pi/2$",r"$\pi$",r"$3\pi/2$",r"$2\pi$"])
plt.plot(x,y)
plt.show()
plt.subplot(211)
plt.plot(x,y1,label = r"$\sin(x)$")

plt.subplot(212)
plt.xlim(-2*np.pi,2*np.pi)
plt.xticks([-2*np.pi,-3*np.pi/2,-1*np.pi,-1*np.pi/2,0,np.pi/2,np.pi,3*np.pi/2,1*np.pi],
           [r"$-2\pi$",r"$-3\pi/2$",r"$-\pi$",r"$-\pi/2$",r"$0$",r"$\pi/2$",r"$\pi$",r"$3\pi/2$",r"$2\pi$"])
plt.plot(x,y)
plt.show()

图例格式

x = np.arange(0,2.1,0.1)
y = np.power(x,3)
y1 = np.power(x,2)
y2 = np.power(x,1)

plt.plot(x,y,ls="-",lw=2,label="$x^{3}$")
plt.plot(x,y1,ls="--",lw=2,c="r",label="$x^{2}$")
plt.plot(x,y2,ls="-",lw=2,c= "y",label="$x^{1}$")

plt.legend(loc="upper left",bbox_to_anchor=(0.05,0.95),ncol= 3,
           title = "power function",shadow=True,fancybox=True)
plt.show()

字体颜色

x = np.linspace(-2,2,1000)
y = np.exp(x)

plt.plot(x,y,ls="--",lw=2,color="g")
plt.title("center demo")
plt.title("Left demo",loc = "left",
          fontdict={'family' : "Times New Roman",
          "size" : "xx-large",
          'style' : "oblique",
          'color' : "r"})
plt.title("Right demo",loc = "right",
          family = "Comic Sans MS",
          size = 20,
          style = "oblique",
          color = "c")
plt.xlim(2,-2)
plt.show()

注意:X轴顺序啊。

添加表格:

labels = "A","B","C","D"
students = [0.35,0.15,0.20,0.30]
explode = (0.1,0.1,0.1,0.1)

colors = ["#8da0cd","#fc8d62","#66c2a5","#ffff99"]
plt.pie(students,
         explode = explode,
         labels = labels,
         autopct = "%1.1f%%",
         startangle = 45,
         shadow = True,
         colors = colors)
plt.title("SS")

colLabels = ["A","B","C","D"]
rowLabels = ["EE"]
studentValue = [[350,150,200,300]]
colColors = ["#8da0cd","#fc8d62","#66c2a5","#ffff99"]
plt.table(cellText=studentValue,
          cellLoc= "center",
          colWidths=[0.1]*4,
          colLabels= colLabels,
          rowLabels= rowLabels,
          colColours= colColors,
          rowLoc= "center",
          loc = "bottom")
plt.show()
             
上一篇下一篇

猜你喜欢

热点阅读