社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
% matplotlib inline
import matplotlib.style as psl
psl.use('_classic_test')
图表类别:线形图、柱状图、密度图,以横纵坐标两个维度为主
同时可延展出多种其他图表样式
plt.plot(kind=‘line’, ax=None, figsize=None, use_index=True, title=None, grid=None, legend=False,
style=None, logx=False, logy=False, loglog=False, xticks=None, yticks=None, xlim=None, ylim=None,
rot=None, fontsize=None, colormap=None, table=False, yerr=None, xerr=None, label=None, secondary_y=False, **kwds)
ts = pd.Series(np.random.randn(1000),index=pd.date_range('1/1/2010',periods=1000))
ts = ts.cumsum()
ts.plot(kind='line', #图表类型
color='r',
style='-gx',
alpha=0.5,
use_index=True, #是否使用数据中给出的index
rot=0, # 旋转刻度标签
ylim=[-50, 50],
yticks=list(range(-50, 50,10)),
title='time series',
legend=True,
label='cad')
plt.grid(True, linestyle = "--",color = "gray", linewidth = "0.5",axis = 'both') # 网格
# Series.plot():series的index为横坐标,value为纵坐标
# kind → line,bar,barh...(折线图,柱状图,柱状图-横...)
# label → 图例标签,Dataframe格式以列名为label
# style → 风格字符串,这里包括了linestyle(-),marker(.),color(g)
# color → 颜色,有color指定时候,以color颜色为准
# alpha → 透明度,0-1
# use_index → 将索引用为刻度标签,默认为True
# rot → 旋转刻度标签,0-360
# grid → 显示网格,一般直接用plt.grid
# xlim,ylim → x,y轴界限
# xticks,yticks → x,y轴刻度值
# figsize → 图像大小
# title → 图名
# legend → 是否显示图例,一般直接用plt.legend()
# 也可以 → plt.plot()
df = pd.DataFrame(np.random.randn(1000, 4), index = ts.index, columns=list('abcd'))
df = df.cumsum()
df.plot(style='--.',
alpha=0.8,
ylim=[-100,100],
figsize=(10,8),
grid=True,
yticks=list(range(-100, 125,25)),
title='text',
subplots=True, #是否将每个系列分成不同的子图
)
plt.grid(True, linestyle='--', axis='both')
# subplots → 是否将各个列绘制到不同图表,默认False
# 也可以 → plt.plot(df)
# 柱状图与堆叠图
# plt.xkcd() #漫画风格
fig,axes=plt.subplots(4, 1, figsize=(12,12))
s = pd.Series(np.random.randint(0,10,16), index=list('abcdfeghjklmnopq'))
df = pd.DataFrame(np.random.rand(10, 3), columns=['a', 'b','c'])
#单系列柱状图
s.plot(kind='bar',ax=axes[0],grid=True,legend=True,label='s', alpha=0.6)
#多系列柱状图
df.plot(kind='bar', ax=axes[1],colormap='Reds_r')
#多系列堆叠图
df.plot(kind='bar',ax=axes[2],colormap='Blues_r', stacked=True)
# stacked → 堆叠
df.plot.barh(ax = axes[3],grid = True,stacked=True,colormap = 'BuGn_r')
# 新版本plt.plot.<kind>
plt.figure(figsize=(10,4))
x = np.arange(10)
y1 = np.random.rand(10)
y2 = np.random.rand(10)
plt.bar(x, y1, width = 0.8, facecolor = 'green', edgecolor= 'black', yerr = y1*0.1)
plt.bar(x, -y2, width = 0.8, facecolor = 'yellow', edgecolor= 'black', yerr = y2*0.1)
# x,y参数:x,y值
# width:宽度比例
# facecolor柱状图里填充的颜色、edgecolor是边框的颜色
# left-每个柱x轴左边界,bottom-每个柱y轴下边界 → bottom扩展即可化为甘特图 Gantt Chart
# align:决定整个bar图分布,默认left表示默认从左边界开始绘制,center会将图绘制在中间位置
# xerr/yerr :x/y方向error bar 误差值
for i, j in zip(x, y1):
plt.text(i-0.2, j+0.1, '%.2f'%j, color='blue')
for i, j in zip(x, y2):
plt.text(i, -j-0.2, '%.2f'%j, color='blue')
# 给图添加text
# zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
# 外嵌图表plt.table()
'''
table(cellText=None, cellColours=None,cellLoc='right', colWidths=None,rowLabels=None, rowColours=None, rowLoc='left',
colLabels=None, colColours=None, colLoc='center',loc='bottom', bbox=None)
'''
data = [[ 66386, 174296, 75131, 577908, 32015],
[ 58230, 381139, 78045, 99308, 160454],
[ 89135, 80552, 152558, 497981, 603535],
[ 78415, 81858, 150656, 193263, 69638],
[139361, 331509, 343164, 781380, 52269]]
columns=('Freeze', 'Wind', 'Flood', 'Quake', 'Hail')
rows = ['%d year'% x for x in (100, 50, 20, 10, 5)]
df = pd.DataFrame(data, columns=('Freeze', 'Wind', 'Flood', 'Quake', 'Hail'),
index=rows)
print(df)
df.plot(kind='bar', grid=True, colormap='Blues_r',stacked=True,
edgecolor='black',rot=0)
#创建堆叠图
plt.table(cellText = data,
cellLoc = 'center',
cellColours = None,
rowLabels = rows,
rowColours = plt.cm.BuPu(np.linspace(0, 0.5,5))[::-1], # BuPu可替换成其他colormap
colLabels = columns,
colColours = plt.cm.Reds(np.linspace(0, 0.5,5))[::-1],
rowLoc='right',
loc='bottom')
# cellText:表格文本
# cellLoc:cell内文本对齐位置
# rowLabels:行标签
# colLabels:列标签
# rowLoc:行标签对齐位置
# loc:表格位置 → left,right,top,bottom
plt.xticks([])
Freeze Wind Flood Quake Hail
100 year 66386 174296 75131 577908 32015
50 year 58230 381139 78045 99308 160454
20 year 89135 80552 152558 497981 603535
10 year 78415 81858 150656 193263 69638
5 year 139361 331509 343164 781380 52269
# 面积图plt.plot.area()
fig,axes = plt.subplots(2,1,figsize = (10,8))
df1 = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
df2 = pd.DataFrame(np.random.randn(10, 4), columns=['a', 'b', 'c', 'd'])
df1.plot.area(colormap = 'Greens_r', alpha = 0.8, ax = axes[0])
df2.plot.area(stacked=False ,colormap = 'Set2',alpha=0.8, ax = axes[1])
# 使用Series.plot.area()和DataFrame.plot.area()创建面积图
# stacked:是否堆叠,默认情况下,区域图被堆叠
# 为了产生堆积面积图,每列必须是正值或全部负值!
# 当数据有NaN时候,自动填充0,所以图标签需要清洗掉缺失值
# 填图
fig, axes = plt.subplots(2, 1, figsize=(10,8))
x = np.linspace(0, 1, 500)
y1 = np.sin(4 * np.pi * x) * np.exp(-5 * x)
y2 = -np.sin(4 * np.pi * x) * np.exp(-5 * x)
axes[0].fill(x, y1, 'r', label = 'y1', alpha = 0.5)
axes[0].fill(x, y2, 'g',alpha = 0.5,label= 'y2')
# 对函数与坐标轴之间的区域进行填充,使用fill函数
# 也可写成:plt.fill(x, y1, 'r',x, y2, 'g',alpha=0.5)
x = np.linspace(0, 5 * np.pi, 1000)
y1 = np.sin(x)
y2 = np.sin(2 * x)
axes[1].fill_between(x, y1, y2, color ='b',alpha=0.5,label='area')
# 填充两个函数之间的区域,使用fill_between函数
# 饼图 plt.pie()
'''
plt.pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None,
radius=None, counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), frame=False, hold=None, data=None)
'''
s = pd.Series(3 * np.random.rand(4), index=['a', 'b', 'c', 'd'], name='series')
plt.axis('equal') # 保证长宽相等
plt.pie(s,
explode = [0.1,0,0,0],
labels = s.index,
colors=['y', 'g', 'b', 'c'],
autopct='%.2f%%',
pctdistance=0.6,
labeldistance = 1.2,
shadow = True,
startangle=0,
radius=2,
frame=False)
print(s)
# 第一个参数:数据
# explode:指定每部分的偏移量
# labels:标签
# colors:颜色
# autopct:饼图上的数据标签显示方式
# pctdistance:每个饼切片的中心和通过autopct生成的文本开始之间的比例
# labeldistance:被画饼标记的直径,默认值:1.1
# shadow:阴影
# startangle:开始角度
# radius:半径
# frame:图框
# counterclock:指定指针方向,顺时针或者逆时针
a 0.783335
b 1.564125
c 2.870229
d 2.809502
Name: series, dtype: float64
# 直方图+密度图
'''
plt.hist(x, bins=10, range=None, normed=False, weights=None, cumulative=False, bottom=None,
histtype='bar', align='mid', orientation='vertical',rwidth=None, log=False, color=None, label=None,
stacked=False, hold=None, data=None, **kwargs)
'''
s = pd.Series(np.random.randn(1000))
s.hist(bins = 20,
histtype = 'bar',
align = 'mid',
orientation = 'vertical',
alpha=0.8,
normed =True,
edgecolor = 'black')
# bin:箱子的宽度
# normed 标准化
# histtype 风格,bar,barstacked,step,stepfilled
# orientation 水平还是垂直{‘horizontal’, ‘vertical’}
# align : {‘left’, ‘mid’, ‘right’}, optional(对齐方式)
s.plot(kind='kde',style='k--')
# 密度图
# 堆叠直方图
plt.figure(num=1)
df = pd.DataFrame({'a': np.random.randn(1000) + 1, 'b': np.random.randn(1000),
'c': np.random.randn(1000) - 1, 'd': np.random.randn(1000)-2},
columns=['a', 'b', 'c','d'])
df.plot.hist(stacked=True,
bins=20,
colormap='Greens_r',
alpha=0.5,
grid=True,
edgecolor='black')
# 使用DataFrame.plot.hist()和Series.plot.hist()方法绘制
# stacked:是否堆叠
df.hist(bins=50)
# 生成多个直方图
#plt.scatter()
# plt.scatter(x, y, s=20, c=None, marker='o', cmap=None, norm=None, vmin=None, vmax=None,
# alpha=None, linewidths=None, verts=None, edgecolors=None, hold=None, data=None, **kwargs)
plt.figure(figsize=(8,6))
x = np.random.randn(1000)
y = np.random.randn(1000)
plt.scatter(x,y,marker='.',
s=np.random.randn(1000)*100,
cmap='Reds',
c=y,
edgecolor='black')
plt.grid(True, linestyle='--')
# s:散点的大小
# c:散点的颜色
# vmin,vmax:亮度设置,标量
# cmap:colormap
# pd.scatter_matrix()散点矩阵
# pd.scatter_matrix(frame, alpha=0.5, figsize=None, ax=None,
# grid=False, diagonal='hist', marker='.', density_kwds=None, hist_kwds=None, range_padding=0.05, **kwds)
df = pd.DataFrame(np.random.randn(100,4),columns = ['a','b','c','d'])
pd.plotting.scatter_matrix(df,figsize=(12,8),
marker='o',
diagonal='kde',
range_padding=0.2)
# diagonal:({‘hist’, ‘kde’}),必须且只能在{‘hist’, ‘kde’}中选择1个 → 每个指标的频率图
# range_padding:(float, 可选),图像在x轴、y轴原点附近的留白(padding),该值越大,留白距离越大,图像远离坐标原点
#创建极坐标轴
s = pd.Series(np.arange(20))
theta = np.arange(0, 2*np.pi, 0.02)
#print(theta)
fig = plt.figure(figsize=(12,6))
ax1=plt.subplot(121,projection='polar')
ax2 = plt.subplot(122)
# 创建极坐标子图
# 还可以写:ax = fig.add_subplot(111,polar=True)
ax1.plot(s, linestyle='--',marker='.', lw=2)
ax2.plot(s, linestyle='--',marker='.', lw=2)
ax1.plot(theta, theta*3, linestyle='--', lw=1)
ax2.plot(theta, theta*3, linestyle='--', lw=1)
plt.grid()
# 创建极坐标图,参数1为角度(弧度制),参数2为value
# lw → 线宽
# 极坐标参数设置
theta=np.arange(0,2*np.pi,0.02
版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/ICERON/article/details/80069680
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!