python下matplotlib 绘图入门

matplotlib

本文是在ipython notebook上编写,是matplot的学习笔记

对一些常用的图形做一些简单的介绍
包括线图,柱状图,饼图等
作图我还是服ggplot,蛤蛤
In [18]:
直接写代码,先导入相关包

import matplotlib.pyplot as plt #导入matplotlib库
import random
random.seed(111)
import numpy as np
%matplotlib inline

In [2]:

first plot 第一个简单的图,随便写些数据

x= [1,2,3]
y=[4,5,2]
x2=[1,2,3]
y2=[10,12,11]
plt.plot(x,y,label="first line")
plt.plot(x2,y2,label="senond")
plt.xlabel("plot num")
plt.ylabel("variance")
plt.title("first graph")
plt.legend()

Out[2]:
<matplotlib.legend.Legend at 0x7a7a2d0>

In [3]:

bar plot 柱状图

x3= [2,4,6,8,10]
y3=[6,7,5,7,6]
x4=[1,3,5,7,9]
y4=[3,4,7,8,5]
plt.bar(x3,y3,label="first",color="red")
plt.bar(x4,y4,label="senond")
plt.xlabel("x")
plt.ylabel("y")
plt.title("first\n graph")
plt.legend()

Out[3]:
<matplotlib.legend.Legend at 0x7bc4830>

In [4]:

histgram 直方图

population_ages=[25,44,7,11,16,49,33,54,43,22,77,54,33,52,39,44,50,76,88,67,90,72]
bins=[0,10,20,30,40,50,60,70,80,90,100]
plt.hist(population_ages,bins,histtype="bar",rwidth=0.8,alpha=0.4)#rwidth宽度,alpha透明度
plt.xlabel("x")
plt.ylabel("y")
plt.title("age distribution")
plt.legend()

C:\Anaconda3\lib\site-packages\matplotlib\axes_axes.py:519: UserWarning: No labelled objects found. Use label='...' kwarg on individual plots. warnings.warn("No labelled objects found. "

In [5]:

散点图sactter

x5= [1,2,3,5,3,8]
y5=[4,5,2,7,6,5]
plt.scatter(x5,y5,label="first",color="g",s=50,marker="*")
​
plt.xlabel("x")
plt.ylabel("y")
plt.title("graph")
plt.legend()

Out[5]:
<matplotlib.legend.Legend at 0xa02cc90>

In [6]:

堆积图stackplot

days=[1,2,3,4,5]
sleeping=[7,8,6,10,7]
eating=[2,3,4,1,2]
working=[9,8,10,11,8]
playing=[6,5,4,2,7]
stackplot不能加Label,但我们可以用其他方法
plt.plot([],[],color="g",label="sleeping",linewidth=5)
plt.plot([],[],color="b",label="eating",linewidth=5)
plt.plot([],[],color="r",label="working",linewidth=5)
plt.plot([],[],color="y",label="playing",linewidth=5)
plt.stackplot(days,sleeping,eating,working,playing,colors=["g","b","r","y"])
plt.xlabel("x")
plt.ylabel("y")
plt.title("graph")
plt.legend()

Out[6]:
<matplotlib.legend.Legend at 0xa038f50>

In [7]:

饼图pie plot

slices=[7,3,10,5]
activities=["sleeping","eating","working","playing"]
cols=["g","b","r","y"]
plt.pie(slices,labels=activities,colors=cols,startangle=90,labeldistance=1.1,radius=1.2,
 autopct="%1.1f%%" ,explode=(0,0.2,0,0),shadow=True)

注意:startangle 角度90,labeldistance label到中心距离,radius图形大小,autopct显示百分比

Out[7]:
([<matplotlib.patches.Wedge at 0xa0bef70>, <matplotlib.patches.Wedge at 0xa0c4e30>, <matplotlib.patches.Wedge at 0xa0c9cd0>, <matplotlib.patches.Wedge at 0xa0ceb70>], [<matplotlib.text.Text at 0xa0c47d0>, <matplotlib.text.Text at 0xa0c9670>, <matplotlib.text.Text at 0xa0ce510>, <matplotlib.text.Text at 0xa0d53b0>], [<matplotlib.text.Text at 0xa0c4b10>, <matplotlib.text.Text at 0xa0c99b0>, <matplotlib.text.Text at 0xa0ce850>, <matplotlib.text.Text at 0xa0d56f0>])

其他参数:

ax1.grid(True,color="g",linestyle="-",linewidth=5) #网格线和参数  
plt.subplot_adjust(left=,right,bottom,top,wspace)# 图形距上下左右距离

In [9]:

subplot 在一个图里创建多个子图

import random

想要不同的图片风格,下面这条语句一定要记得

from matplotlib import style
style.use("ggplot")

可以使用不同的style,如著名的fivethirtyeight,还有ggplot,查看style.library,还可以自定义style。吼啊!

https://tonysyu.github.io/raw_content/matplotlib-style-gallery/gallery.html

fig=plt.figure()
def create_plot():
 xs =[]
 ys = []
 for i in range(10):
 x=i
 y=random.randrange(10)
 xs.append(x)
 ys.append(y)
 return xs,ys
ax1 = fig.add_subplot(211) #subplot ,2高1宽1第几个
ax2 = fig.add_subplot(212)

如果想要上面两个,下面一个,共三个图形,可以

ax1(221),ax2(222),ax3(212)
x,y=create_plot()
ax1.plot(x,y)
x,y=create_plot()
ax2.plot(x,y)


Out[9]:
[<matplotlib.lines.Line2D at 0x4ab8b50>]

In [10]:

另一种subplot方法

ax3=plt.subplot2grid((6,1),(0,0),rowspan=1,colspan=1)
ax4=plt.subplot2grid((6,1),(1,0),rowspan=4,colspan=1)#还可以
sharex=ax3
ax5=plt.subplot2grid((6,1),(5,0),rowspan=1,colspan=1)
x,y=create_plot()
ax3.plot(x,y)
x,y=create_plot()
ax4.plot(x,y)
x,y=create_plot()
ax5.plot(x,y)

Out[10]:
[<matplotlib.lines.Line2D at 0x4b3cf10>]

In [15]:

fill_between 填充颜色到曲线中

from matplotlib import style
style.use("fivethirtyeight")#换个非常著名的fivethirtyeight
a=np.random.randn(100).cumsum()+50
b=np.random.randn(100).cumsum()+50
c=range(100)
fig=plt.figure()
ax6 = fig.add_subplot(211)
ax7 =fig.add_subplot(212)
ax6.plot(c,a)
ax6.plot(c,b)
ax6.fill_between(c,a,b,where=(a<b),facecolor='y',edgecolor='k',alpha=0.5)
ax6.fill_between(c,a,b,where=(a>b),facecolor='b',edgecolor='k',alpha=0.5)
ax7.plot(c,a-b)
#这样看起来更清楚了

Out[15]:
[<matplotlib.lines.Line2D at 0x4eb2410>]

In [20]:

3d plot 3D绘图

from mpl_toolkits.mplot3d import axes3d
fig=plt.figure()
ax01 = fig.add_subplot(111,projection = "3d")
x = [1,2,3,4,5,6,7,8,9]
y = [4,3,5,6,2,5,7,6,3]
z = [4,6,7,3,7,4,8,5,4]
ax01.plot_wireframe(x,y,z)
ax01.set_xlabel("x label")
ax01.set_ylabel("y label")
ax01.set_zlabel("x label")

Out[20]:
<matplotlib.text.Text at 0xa1bb8d0>

还有basemap,暂时不做了 matplotlib里面还有很多toolkit,比如seaborn http://matplotlib.org/mpl_toolkits/index.html?highlight=basemap 想找自己喜欢的colors可以到官网 named_colors
matplotlib 2.0 有个新的更好的colormap "viridis",原来的默认colormap真心不漂亮
以上! 只是做了一点微小的工作

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容