python畫圖


 

正弦圖像:

#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()

  

 

繪制多軸圖

subplot(numRows, numCols, plotNum)
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("rgbyck"):
    plt.subplot(330+idx+1, axisbg=color)
plt.show()

plt.subplot(221) # 第一行的左圖
plt.subplot(222) # 第一行的右圖
#第二行全占
plt.subplot(212) # 第二整行
plt.show()

 

配置文件

>>> import matplotlib

>>> matplotlib.get_configdir()

'/Users/similarface/.matplotlib'

 

 

刻度定義:

#coding:utf-8
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 "0"
    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()

 

畫點圖

import matplotlib.pyplot as plt
from sklearn.datasets import load_boston
X1 = load_boston()['data'][:, [8]]
X2 = load_boston()['data'][:, [10]]
plt.scatter(X1,X2, marker = 'o')
plt.show()

 

畫三維圖

m=pd.read_csv(sportinte)
x,y,z = m['ydra'],m['zyd'],m['rs12612420']
ax=plt.subplot(111,projection='3d') #創建一個三維的繪圖工程
ax.scatter(x[:],y[:],z[:],c='r')
#將數據點分成三部分畫,在顏色上有區分度
plt.scatter(y,z, marker = 'o')
ax.set_zlabel('rs12612420') #坐標軸
ax.set_ylabel(u'周運動')
ax.set_xlabel(u'運動熱愛')
plt.show()

 

#散點柱狀圖

#coding:utf-8
import  numpy as np
#pip install seaborn
import seaborn as sns
sns.set(style="whitegrid", color_codes=True)
np.random.seed(sum(map(ord, "categorical")))
titanic = sns.load_dataset("titanic")
tips = sns.load_dataset("tips")
iris = sns.load_dataset("iris")
#在帶狀圖中,散點圖通常會重疊。這使得很難看到數據的完全分布
sns.stripplot(x="day", y="total_bill", data=tips)
sns.plt.show()

#加入隨機抖動”來調整位置
sns.stripplot(x="day", y="total_bill", data=tips, jitter=True);

#避免重疊點
sns.swarmplot(x="day", y="total_bill", data=tips)

#加入說明label
sns.swarmplot(x="day", y="total_bill", hue="sex", data=tips);

sportinte="/Users/similarface/Documents/sport耐力與爆發/sportinter.csv"
m=pd.read_csv(sportinte)
sns.swarmplot(x="ydra", y="zyd", hue="rs12612420", data=m);
sns.plt.show()

 箱圖

sportinte="/Users/similarface/Documents/sport耐力與爆發/sportinter.csv"
m=pd.read_csv(sportinte)
sns.boxplot(x="ydra", y="zyd", hue="rs12612420", data=m)
sns.plt.show()

小提琴圖

sportinte="/Users/similarface/Documents/sport耐力與爆發/sportinter.csv"
m=pd.read_csv(sportinte)
sns.violinplot(x="ydra", y="zyd", hue="rs12612420", data=m)
sns.plt.show()

 

sportinte="/Users/similarface/Documents/sport耐力與爆發/sportinter.csv"
m=pd.read_csv(sportinte)
sns.violinplot(x="ydra", y="zyd", hue="rs12612420", data=m,bw=.1, scale="count", scale_hue=False)
sns.plt.show()

sns.violinplot(x="day", y="total_bill", hue="sex", data=tips, split=True);
sns.plt.show()

 

#加入每個觀測值
sns.violinplot(x="day", y="total_bill", hue="sex", data=tips,
               split=True, inner="stick", palette="Set3");

#加入點柱狀圖和小提琴圖
sns.violinplot(x="day", y="total_bill", data=tips, inner=None) sns.swarmplot(x="day", y="total_bill", data=tips, color="w", alpha=.5);

 柱狀

sns.barplot(x="sex", y="survived", hue="class", data=titanic);
sns.plt.show()

#count 計數圖
sns.countplot(x="deck", data=titanic, palette="Greens_d");
sns.countplot(y="deck", hue="class", data=titanic, palette="Greens_d");
#泰坦尼克號獲取與船艙等級
sns.pointplot(x="sex", y="survived", hue="class", data=titanic)

sns.factorplot(x="time", y="total_bill", hue="smoker", col="day", data=tips, kind="box", size=4, aspect=.5);
sns.plt.show()

g = sns.PairGrid(tips,
                 x_vars=["smoker", "time", "sex"],
                 y_vars=["total_bill", "tip"],
                 aspect=.75, size=3.5)
g.map(sns.violinplot, palette="pastel");
sns.plt.show()

#當有很多因素的時候怎么去看這些是否有潛在關系

import matplotlib.pyplot as plt
import seaborn as sns
_ = sns.pairplot(df[:50], vars=[1,2,3,4,5,6,7,8,9,10,11], hue="class", size=1)
plt.show()

可以發現一些端倪

 

ref:http://seaborn.pydata.org/tutorial/categorical.html  

畫餅圖:

#coding:utf-8
__author__ = 'similarface'
'''
耳垢項目
'''
import pandas as pd
import seaborn as sns
from scipy.stats import spearmanr
meat_to_phenotypes = {
  'Dry': 1,
  'Wet': 0,
  'Un': 2,
}

meat_to_genotype = {
  'TT': 2,
  'CT': 1,
  'CC': 0,
}
filepath="/Users/similarface/Documents/phenotypes/耳垢/ergou20170121.txt"
data=pd.read_csv(filepath,sep="\t")
data['phenotypesid'] = data['phenotypes'].map(meat_to_phenotypes)
data['genotypeid'] = data['genotype'].map(meat_to_genotype)
#######################################################################################
#均線圖
#剔除不清楚
#####
# data=data[data.phenotypesid!=2]
# p=sns.pointplot(x="genotype", y='phenotypesid', data=data,markers="o")
# p.axes.set_title(u"均線圖[濕耳0干耳1]")
#####
#######################################################################################



#######################################################################################
#####
#聯結圖
# p=sns.jointplot(x="genotypeid", y="phenotypesid", data=data,stat_func=spearmanr)
#####
#######################################################################################


#######################################################################################
#####
# data=data[data.phenotypesid!=2]
# sns.countplot(x="genotype", hue="phenotypes", data=data)
#p.axes.set_title(u"柱狀圖[濕耳0干耳1]")
#####
#######################################################################################

#sns.plt.show()

#######################################################################################
#####
import matplotlib.pyplot as plt

#
data=data[data.phenotypesid!=2]
plt.subplot(221)
g=data.groupby(['phenotypes'])
label_list=g.count().index
plt.pie(g.count()['genotype'],labels=label_list,autopct="%1.1f%%")
plt.title(u"問卷統計餅圖(不含Unkown)")


datag=data[data.genotype=='TT']
g=datag.groupby(['phenotypes'])
label_list=g.count().index
plt.subplot(222)
plt.pie(g.count()['genotype'],labels=label_list,autopct="%1.1f%%")
plt.title(u"耳垢TT")


datag=data[data.genotype=='CT']
g=datag.groupby(['phenotypes'])
label_list=g.count().index
plt.subplot(223)
plt.pie(g.count()['genotype'],labels=label_list,autopct="%1.1f%%")
plt.title(u"耳垢CT")


datag=data[data.genotype!='TT']
g=datag.groupby(['phenotypes'])
label_list=g.count().index
plt.subplot(224)
plt.pie(g.count()['genotype'],labels=label_list,autopct="%1.1f%%")
plt.title(u"耳垢!=TT")

plt.show()
#####
#######################################################################################

 

 

#coding:utf-8
__author__ = 'similarface'
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()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM