沉淀再出发:用python画各种图表
一、前言
最近需要用python来做一些统计和画图,因此做一些笔记。
二、python画各种图表
2.1、使用turtle来画图
import turtle as t #turtle库是python的内部库,直接import使用即可
import time def draw_diamond(turt):
for i in range(1,3):
turt.forward(100) #向前走100步
turt.right(45) #海龟头向右转45度
turt.forward(100) #继续向前走100步
turt.right(135) #海龟头再向右转135度 def draw_art():
window = t.Screen() #创建画布
window.bgcolor("green") #设置画布颜色
brad = t.Turtle() #创建一个Turtle的实例
brad.shape('turtle') #形状是一个海归turtle,也可以是圆圈circle,箭头(默认)等等 brad.color("red") #海龟的颜色是红色red,橙色orange等
brad.speed('fast') #海龟画图的速度是快速fast,或者slow等 for i in range(1,37): #循环36次
draw_diamond(brad) #海龟画一个形状/花瓣,也就是菱形
brad.right(10) #后海龟头向右旋转10度 brad.right(90) #当图形画完一圈后,把海龟头向右转90度
brad.forward(300) #画一根长线/海龟往前走300步 window.exitonclick() #点击屏幕退出 draw_art() #调用函数开始画图 t.color("red", "yellow")
t.speed(10)
t.begin_fill()
for _ in range(50):
t.forward(200)
t.left(170)
end_fill()
time.sleep(1)
2.2、画坐标系
import sys
import math
import random
import matplotlib.pyplot as plt
import pylab as pl
import numpy as np pl.mpl.rcParams['font.sans-serif'] = ['FangSong'] # 指定默认字体
pl.mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题 x = range(10) # 横轴的数据
y = [i*i for i in x] # 纵轴的数据
y1 = [i*i+123 for i in x] # 纵轴的数据
pl.title('title zyr')
pl.plot(x, y, '1m:', label=u'compare') # 加上label参数添加图例
pl.plot(x, y1, '>r--', label=u'set other') # 加上label参数添加图例
pl.xlabel(u"横轴的数据")
pl.ylabel(u"纵轴的数据")
pl.legend() # 让图例生效
pl.show() # 显示绘制出的图
import sys
import math
import random
import matplotlib.pyplot as plt
import pylab as pl
import numpy as np pl.mpl.rcParams['font.sans-serif'] = ['FangSong'] # 指定默认字体
pl.mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题 x = list(range(10))+[100]
y = [i*i for i in x]
pl.plot(x, y, 'ob-', label=u'y=x^2')
pl.xlim(-1, 11) # 限定横轴的范围
pl.ylim(-1, 110) # 限定纵轴的范围 pl.show() # 显示绘制出的图
颜色(color 简写为 c):
# 蓝色: 'b' (blue)
# 绿色: 'g' (green)
# 红色: 'r' (red)
# 蓝绿色(墨绿色): 'c' (cyan)
# 红紫色(洋红): 'm' (magenta)
# 黄色: 'y' (yellow)
# 黑色: 'k' (black)
# 白色: 'w' (white) # 线型(linestyle 简写为 ls):
# 实线: '-'
# 虚线: '--'
# 虚点线: '-.'
# 点线: ':'
# 点: '.' # 点型(标记marker):
# 像素: ','
# 圆形: 'o'
# 上三角: '^'
# 下三角: 'v'
# 左三角: '<'
# 右三角: '>'
# 方形: 's'
# 加号: '+'
# 叉形: 'x'
# 棱形: 'D'
# 细棱形: 'd'
# 三脚架朝下: '1'(像'丫')
# 三脚架朝上: '2'
# 三脚架朝左: '3'
# 三脚架朝右: '4'
# 六角形: 'h'
# 旋转六角形: 'H'
# 五角形: 'p'
# 垂直线: '|'
# 水平线: '_'
2.3、直方图
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(19680801)
mu1, sigma1 = 100, 15
mu2, sigma2 = 80, 15
x1 = mu1 + sigma1 * np.random.randn(10000)
x2 = mu2 + sigma2 * np.random.randn(10000)
# the histogram of the data
# 50:将数据分成50组
# facecolor:颜色;alpha:透明度
# density:是密度而不是具体数值
n1, bins1, patches1 = plt.hist(x1, 50, density=True, facecolor='g', alpha=1)
n2, bins2, patches2 = plt.hist(x2, 50, density=True, facecolor='r', alpha=0.2)
# n:概率值;bins:具体数值;patches:直方图对象。
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(110, .025, r'$\mu=100,\ \sigma=15$')
plt.text(50, .025, r'$\mu=80,\ \sigma=15$')
# 设置x,y轴的具体范围
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()
2.4、扇形图/饼图
import matplotlib.pyplot as plt
import time
from pylab import mpl
import numpy as np
import matplotlib.animation as animation
import time mpl.rcParams['font.sans-serif'] = ['FangSong'] # 指定默认字体
mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题 data = {'': 106, '': 704, '': 491, '': 24, '': 6, '': 23, '': 11,
'': 29, '': 23, '': 31, '': 31, '': 24, '': 18, '': 33,
'': 49, '': 82, '': 57,'': 71, '': 50, '': 68, '': 136,
'': 103, '': 88, '': 58, '': 185, '': 62,'': 61, '': 90,
'': 57, '': 102, '': 59,'': 27, '': 142, '': 159, '': 347,
'': 64, '': 87, '': 145, '': 645, '': 671}
source_data = sorted(data.items(), key=lambda x: x[1], reverse=True)
print(source_data)
labels = [source_data[i][0][:4] for i in range(len(source_data))] # 设置标签
fracs = [source_data[i][1] for i in range(len(source_data))]
explode = [x * 0.01 for x in range(len(source_data))] # 与labels一一对应,数值越大离中心区越远
plt.axes(aspect=1) # 设置X轴 Y轴比例
# labeldistance标签离中心距离 pctdistance百分百数据离中心区距离 autopct 百分比的格式 shadow阴影
plt.pie(x=fracs, labels=labels, explode=explode, autopct='%3.1f %%',
shadow=False, labeldistance=1.1, startangle=0, pctdistance=0.8, center=(-1, 0))
# 控制位置:bbox_to_anchor数组中,前者控制左右移动,后者控制上下。ncol控制 图例所列的列数。默认值为1。fancybox 圆边
plt.legend(loc=7, bbox_to_anchor=(1.2, 0.80), ncol=3, fancybox=True, shadow=True, fontsize=8)
plt.show()
import matplotlib.pyplot as plt
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
# 设置分离的距离,0表示不分离
explode = (0, 0.1, 0, 0)
plt.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
shadow=True, startangle=90)
# Equal aspect ratio 保证画出的图是正圆形
plt.axis('equal')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# 设置每环的宽度
size = 0.3
vals = np.array([[60., 32.], [37., 40.], [29., 10.]])
# 通过get_cmap随机获取颜色
cmap = plt.get_cmap("tab20c")
outer_colors = cmap(np.arange(3)*4)
inner_colors = cmap(np.array([1, 2, 5, 6, 9, 10]))
print(vals.sum(axis=1))
# [92. 77. 39.]
plt.pie(vals.sum(axis=1), radius=1, colors=outer_colors,
wedgeprops=dict(width=size, edgecolor='w'))
print(vals.flatten())
# [60. 32. 37. 40. 29. 10.]
plt.pie(vals.flatten(), radius=1-size, colors=inner_colors,
wedgeprops=dict(width=size, edgecolor='w'))
# equal 使得为正圆
plt.axis('equal')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(19680801)
N = 10
theta = np.linspace(0.0, 2 * np.pi, N, endpoint=False)
radii = 10 * np.random.rand(N)
width = np.pi / 4 * np.random.rand(N)
ax = plt.subplot(111, projection='polar')
bars = ax.bar(theta, radii, width=width, bottom=0.0)
# left表示从哪开始,
# radii表示从中心点向边缘绘制的长度(半径)
# width表示末端的弧长
# 自定义颜色和不透明度
for r, bar in zip(radii, bars):
bar.set_facecolor(plt.cm.viridis(r / 10.))
bar.set_alpha(0.5)
plt.show()
2.5、动图
import matplotlib.pyplot as plt
import time
from pylab import mpl
import numpy as np
import matplotlib.animation as animation
import time mpl.rcParams['font.sans-serif'] = ['FangSong'] # 指定默认字体
mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题 # Fixing random state for reproducibility
np.random.seed(196)
# 初始数据绘图
dis = np.zeros(40)
dis2 = dis
fig, ax = plt.subplots()
line, = ax.plot(dis)
ax.set_ylim(-1, 1)
plt.grid(True)
ax.set_ylabel("distance: m")
ax.set_xlabel("time") def update(frame):
global dis
global dis2
global line
# 读入模拟
a = np.random.rand() * 2 - 1
time.sleep(np.random.rand() / 10)
# 绘图数据生成
dis[0:-1] = dis2[1:]
dis[-1] = a
dis2 = dis
# 绘图
line.set_ydata(dis)
# 颜色设置
plt.setp(line, 'color', 'c', 'linewidth', 2.0)
ani = animation.FuncAnimation(fig, update, frames=None, interval=100)
plt.show()
2.6、画其他图形
import matplotlib.pyplot as plt
plt.rcdefaults() import numpy as np
import matplotlib.pyplot as plt
import matplotlib.path as mpath
import matplotlib.lines as mlines
import matplotlib.patches as mpatches
from matplotlib.collections import PatchCollection def label(xy, text):
y = xy[1] - 0.15 # shift y-value for label so that it's below the artist
plt.text(xy[0], y, text, ha="center", family='sans-serif', size=14) fig, ax = plt.subplots()
# create 3x3 grid to plot the artists
grid = np.mgrid[0.2:0.8:3j, 0.2:0.8:3j].reshape(2, -1).T patches = [] # add a circle
circle = mpatches.Circle(grid[0], 0.1, ec="none")
patches.append(circle)
label(grid[0], "Circle") # add a rectangle
rect = mpatches.Rectangle(grid[1] - [0.025, 0.05], 0.05, 0.1, ec="none")
patches.append(rect)
label(grid[1], "Rectangle") # add a wedge
wedge = mpatches.Wedge(grid[2], 0.1, 30, 270, ec="none")
patches.append(wedge)
label(grid[2], "Wedge") # add a Polygon
polygon = mpatches.RegularPolygon(grid[3], 5, 0.1)
patches.append(polygon)
label(grid[3], "Polygon") # add an ellipse
ellipse = mpatches.Ellipse(grid[4], 0.2, 0.1)
patches.append(ellipse)
label(grid[4], "Ellipse") # add an arrow
arrow = mpatches.Arrow(grid[5, 0] - 0.05, grid[5, 1] - 0.05, 0.1, 0.1, width=0.1)
patches.append(arrow)
label(grid[5], "Arrow") # add a path patch
Path = mpath.Path
path_data = [
(Path.MOVETO, [0.018, -0.11]),
(Path.CURVE4, [-0.031, -0.051]),
(Path.CURVE4, [-0.115, 0.073]),
(Path.CURVE4, [-0.03 , 0.073]),
(Path.LINETO, [-0.011, 0.039]),
(Path.CURVE4, [0.043, 0.121]),
(Path.CURVE4, [0.075, -0.005]),
(Path.CURVE4, [0.035, -0.027]),
(Path.CLOSEPOLY, [0.018, -0.11])
]
codes, verts = zip(*path_data)
path = mpath.Path(verts + grid[6], codes)
patch = mpatches.PathPatch(path)
patches.append(patch)
label(grid[6], "PathPatch") # add a fancy box
fancybox = mpatches.FancyBboxPatch(
grid[7] - [0.025, 0.05], 0.05, 0.1,
boxstyle=mpatches.BoxStyle("Round", pad=0.02))
patches.append(fancybox)
label(grid[7], "FancyBboxPatch") # add a line
x, y = np.array([[-0.06, 0.0, 0.1], [0.05, -0.05, 0.05]])
line = mlines.Line2D(x + grid[8, 0], y + grid[8, 1], lw=5., alpha=0.3)
label(grid[8], "Line2D") colors = np.linspace(0, 1, len(patches))
collection = PatchCollection(patches, cmap=plt.cm.hsv, alpha=0.3)
collection.set_array(np.array(colors))
ax.add_collection(collection)
ax.add_line(line) plt.subplots_adjust(left=0, right=1, bottom=0, top=1)
plt.axis('equal')
plt.axis('off') plt.show()
2.7、画点图
from numpy import *;
import numpy as np
import matplotlib.pyplot as plt N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = np.pi * (15 * np.random.rand(N))**2
plt.scatter(x, y, s=area, c=colors, alpha=0.5, marker=(9, 3, 30))
plt.show()
2.8、画数学曲线
#coding:utf-8
import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(0,10,1000)
y=np.sin(x)
z=np.cos(x**2)
#控制图形的长和宽单位为英寸,
# 调用figure创建一个绘图对象,并且使它成为当前的绘图对象。
plt.figure(figsize=(8,4))
#$可以让字体变得跟好看
#给所绘制的曲线一个名字,此名字在图示(legend)中显示。
# 只要在字符串前后添加"$"符号,matplotlib就会使用其内嵌的latex引擎绘制的数学公式。
#color : 指定曲线的颜色
#linewidth : 指定曲线的宽度
plt.plot(x,y,label="$sin(x)$",color="red",linewidth=2)
#b-- 曲线的颜色和线型
plt.plot(x,z,"b--",label="$cos(x^2)$")
#设置X轴的文字
plt.xlabel("Time(s)")
#设置Y轴的文字
plt.ylabel("Volt")
#设置图表的标题
plt.title("PyPlot First Example")
#设置Y轴的范围
plt.ylim(-1.2,1.2)
#显示图示
plt.legend()
#显示出我们创建的所有绘图对象。
plt.show()
#coding:utf-8
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(0,5,0.1)
## plot返回一个列表,通过line,获取其第一个元素
line,=plt.plot(x,x*x)
# 调用Line2D对象的set_*方法设置属性值 是否抗锯齿
line.set_antialiased(False)
# 同时绘制sin和cos两条曲线,lines是一个有两个Line2D对象的列表
lines = plt.plot(x, np.sin(x), x, np.cos(x))
## 调用setp函数同时配置多个Line2D对象的多个属性值
plt.setp(lines, color="r", linewidth=2.0)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0., 5., 0.2)
# 红色破折号, 蓝色方块 ,绿色三角块
plt.plot(x, x, 'r--', x, x**2, 'bs', x, x**3, 'g^')
plt.show()
2.9.画多个子图
import matplotlib.pyplot as plt
'''
subplot(numRows, numCols, plotNum)
numRows行 * numCols列个子区域
如果numRows,numCols和plotNum这三个数都小于10的话,可以把它们缩写为一个整数,
例如subplot(323)和subplot(3,2,3)是相同的
'''
for idx, color in enumerate("rgbyckbyc"):
plt.subplot(330+idx+1, facecolor=color)
plt.show()
plt.subplot(221) # 第一行的左图
plt.subplot(222) # 第一行的右图
#第二行全占
plt.subplot(212) # 第二整行
plt.show() plt.subplot(331, facecolor='r')
plt.show()
2.10、标记刻度
import matplotlib.pyplot as pl
from matplotlib.ticker import MultipleLocator, FuncFormatter
import numpy as np
x = np.arange(0, 4*np.pi, 0.01)
y = np.sin(x)
pl.figure(figsize=(8,4))
pl.plot(x, y)
ax = pl.gca() def pi_formatter(x, pos):
"""
比较罗嗦地将数值转换为以pi/4为单位的刻度文本
"""
m = np.round(x / (np.pi/4))
n = 4
if m%2==0: m, n = m/2, n/2
if m%2==0: m, n = m/2, n/2
if m == 0:
return ""
if m == 1 and n == 1:
return "$\pi$"
if n == 1:
return r"$%d \pi$" % m
if m == 1:
return r"$\frac{\pi}{%d}$" % n
return r"$\frac{%d \pi}{%d}$" % (m,n)
# 设置两个坐标轴的范围
pl.ylim(-1.5,1.5)
pl.xlim(0, np.max(x))
# 设置图的底边距
pl.subplots_adjust(bottom = 0.15)
pl.grid() #开启网格
# 主刻度为pi/4
ax.xaxis.set_major_locator( MultipleLocator(np.pi/4) )
# 主刻度文本用pi_formatter函数计算
ax.xaxis.set_major_formatter( FuncFormatter( pi_formatter ) )
# 副刻度为pi/20
ax.xaxis.set_minor_locator( MultipleLocator(np.pi/20) )
# 设置刻度文本的大小
for tick in ax.xaxis.get_major_ticks():
tick.label1.set_fontsize(16)
pl.show()
2.11、三维图
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np def fun(x,y):
#return np.power(x,2)+np.power(y,2)
return 2*(x*0.8+y*0.1)*(x*0.2+y*0.9)*(x*0.3+y*0.7)*(x*0.3+y*0.7)*(x*0.4+y*0.7)*(x*0.4+y*0.7) def fun2(xx,yy):
return xx fig1=plt.figure()
ax=Axes3D(fig1)
X=np.arange(0,1,0.01)
Y=np.arange(0,1,0.01) XX=np.arange(0,1,0.01)
YY=np.arange(1,0,-0.01) ZZ=np.arange(0,1,0.01) ZZ,ZZ=np.meshgrid(ZZ,ZZ) #ZZ=fun2(XX,YY)
X,Y=np.meshgrid(X,Y)
Z=fun(X,Y)
plt.title("This is main title")
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.cm.coolwarm) ax.plot_surface(XX, YY, ZZ, rstride=1, cstride=1, cmap=plt.cm.coolwarm) ax.set_xlabel(u'θ1', color='r')
ax.set_ylabel(u'θ2', color='g')
ax.set_zlabel('z label', color='b')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
data = np.random.randint(0, 255, size=[40, 40, 40])
x, y, z = data[0], data[1], data[2]
ax = plt.subplot(111, projection='3d') # 创建一个三维的绘图工程
# 将数据点分成三部分画,在颜色上有区分度
ax.scatter(x[:10], y[:10], z[:10], c='y') # 绘制数据点
ax.scatter(x[10:20], y[10:20], z[10:20], c='r')
ax.scatter(x[30:40], y[30:40], z[30:40], c='g')
ax.set_zlabel('Z') # 坐标轴
ax.set_ylabel('Y')
ax.set_xlabel('X')
plt.show()
from matplotlib import pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
# 具体函数方法可用 help(function) 查看,如:help(ax.plot_surface)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='rainbow')
plt.show()
2.12、画3d柱状图
#-*- coding:utf-8 -*-
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import random
import matplotlib.dates as mdates from mpl_toolkits.mplot3d import Axes3D
#generate random numbers
Query_times1=range(0,50)
Query_times2=range(0,30)
list_random1=random.sample(Query_times1,25)
list_random2=random.sample(Query_times2,25)
mpl.rcParams['font.size'] = 8 fig = plt.figure()
ax = fig.add_subplot(111, projection='3d') xs = np.arange(1,26)
ys =list_random1
ys2=list_random2
ys3=list_random1
ys4=list_random2
ys5=list_random1
ys6=list_random2
ys7=list_random1
ys8=list_random2 z1=3
total_width, n = 0.8, 2
width = total_width / n
color =plt.cm.Set2((np.arange(plt.cm.Set2.N)))
p1=ax.bar(xs, ys, z1, zdir='y', color='#FF0080', alpha=0.8,width=width,label='h=3,DA')
p2=ax.bar(xs + width, ys2, z1, zdir='y', color='CYAN', alpha=0.8,width=width,label='h=3,DGA') z2=4
total_width, n = 0.8, 2
width = total_width / n
color =plt.cm.Set2((np.arange(plt.cm.Set2.N)))
p3=ax.bar(xs, ys3, z2, zdir='y', color='b', alpha=0.8,width=width,label='h=4,DA')
p4=ax.bar(xs + width, ys4, z2, zdir='y', color='#9AFF02', alpha=0.8,width=width,label='h=4,DGA') z3=5
total_width, n = 0.8, 2
width = total_width / n
color =plt.cm.Set2((np.arange(plt.cm.Set2.N)))
p5=ax.bar(xs, ys5, z3, zdir='y', color='#FF8000', alpha=0.8,width=width,label='h=5,DA')
p6=ax.bar(xs + width, ys6, z3, zdir='y', color='violet', alpha=0.8,width=width,label='h=5,DGA') z4=6
total_width, n = 0.8, 2
width = total_width / n
color =plt.cm.Set2((np.arange(plt.cm.Set2.N)))
p7=ax.bar(xs, ys7, z4, zdir='y', color='r', alpha=0.8,width=width,label='h=6,DA')
p8=ax.bar(xs + width, ys8, z4, zdir='y', color='#0072E3', alpha=0.8,width=width,label='h=6,DGA') # ax.xaxis.set_major_locator(mpl.ticker.FixedLocator(xs))
# ax.yaxis.set_major_locator(mpl.ticker.FixedLocator(ys)) ax.set_xlabel('k-')
ax.set_ylabel('Spatial hierarchy (h)')
ax.set_zlabel('Count')
# plt.legend(loc='upper left')
#plt.legend(loc='upper left', bbox_to_anchor=(0.0,0.6),ncol=1,fancybox=True,shadow=False)#Control the position of the legend
plt.show()
2.13、柱状图、并列柱状图
import numpy as np
import matplotlib.animation as animation
import time mpl.rcParams['font.sans-serif'] = ['FangSong'] # 指定默认字体
mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题 source_data = {'mock_verify': 369, 'mock_notify': 192, 'mock_sale': 517} # 设置原始数据 for a, b in source_data.items():
plt.text(a, b + 0.05, '%.0f' % b, ha='center', va='bottom', fontsize=11) # ha 文字指定在柱体中间, va指定文字位置 fontsize指定文字体大小 # 设置X轴Y轴数据,两者都可以是list或者tuple
x_axis = tuple(source_data.keys())
y_axis = tuple(source_data.values())
plt.bar(x_axis, y_axis, color='rg') # 如果不指定color,所有的柱体都会是一个颜色 plt.xlabel(u"渠道名") # 指定x轴描述信息
plt.ylabel(u"访问量") # 指定y轴描述信息
plt.title("渠道访问量统计表") # 指定图表描述信息
plt.ylim(0, 600) # 指定Y轴的高度
# plt.savefig('{}.png'.format(time.strftime('%Y%m%d%H%M%S'))) # 保存为图片
plt.show()
import numpy as np
import matplotlib.pyplot as plt
x = [1,2] #横坐标
y = [3,4] #第一个纵坐标
y1 = [5,6] #第二个纵坐标
x = np.arange(len(x)) #首先用第一个的长度作为横坐标
width = 0.05 #设置柱与柱之间的宽度
fig,ax = plt.subplots()
ax.bar(x,y,width,alpha = 0.9)
ax.bar(x+width,y1,width,alpha = 0.9,color= 'red')
ax.set_xticks(x +width/2)#将坐标设置在指定位置
ax.set_xticklabels(x)#将横坐标替换成
plt.show()
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt name_list = ['Monday','Tuesday','Friday','Sunday']
num_list = [1.5,0.6,7.8,6]
num_list1 = [1,2,3,1]
x =list(range(len(num_list)))
total_width, n = 0.8, 2
width = total_width / n plt.bar(x, num_list, width=width, label='boy',fc = 'y')
for i in range(len(x)):
x[i] = x[i] + width
plt.bar(x, num_list1, width=width, label='girl',tick_label = name_list,fc = 'r')
plt.legend()
plt.show()
import numpy as np
import matplotlib.pyplot as plt
size = 5
a = np.random.random(size)
b = np.random.random(size)
c = np.random.random(size)
x = np.arange(size)
# 有多少个类型,只需更改n即可
total_width, n = 0.8, 3
width = total_width / n
# 重新拟定x的坐标
x = x - (total_width - width) / 2
# 这里使用的是偏移
plt.bar(x, a, width=width, label='a')
plt.bar(x + width, b, width=width, label='b')
plt.bar(x + 2 * width, c, width=width, label='c')
plt.legend()
plt.show()
2.13、堆叠柱状图
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt name_list = ['Monday','Tuesday','Friday','Sunday']
num_list = [1.5,0.6,7.8,6]
num_list1 = [1,2,3,1]
plt.bar(range(len(num_list)), num_list, label='boy',fc = 'y')
plt.bar(range(len(num_list)), num_list1, bottom=num_list, label='girl',tick_label = name_list,fc = 'r')
plt.legend()
plt.show()
import numpy as np
import matplotlib.pyplot as plt
size = 5
a = np.random.random(size)
b = np.random.random(size)
c = np.random.random(size)
x = np.arange(size)
# 这里使用的是偏移
plt.bar(x, a, width=0.5, label='a',fc='r')
plt.bar(x, b, bottom=a, width=0.5, label='b', fc='g')
plt.bar(x, c, bottom=a+b, width=0.5, label='c', fc='b')
plt.ylim(0, 2.5)
plt.legend()
plt.grid(True)
plt.show()
2.14、横排柱状图
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt name_list = ['Monday','Tuesday','Friday','Sunday']
num_list = [1.5,0.6,7.8,6]
plt.barh(range(len(num_list)), num_list,tick_label = name_list)
plt.show()
三、总结
使用python中的库,我们可以按照自己的想法来画图,但是需要注意一些细节上的东西,比如尺寸和刻度,比如颜色,字体,以及相应对比的数据,特别是用于数据分析上面的对比,我们需要重点掌握。