Python数据分析基础_Clinton著_陈广欣译_图表_笔记

版权声明:个人随手学习笔记,任何欠妥之处,还望海涵指正~~~ https://blog.csdn.net/sinat_41842926/article/details/84971284

因本人刚开始写博客,学识经验有限,如有不正之处望读者指正,不胜感激;也望借此平台留下学习笔记以温故而知新。这个系列主要是Python数据分析基础的学习笔记。

采用基本 matplotlib 包创建数据统计图
创建一个垂直条形图

#创建一个垂直条形图
import matplotlib.pyplot as plt
# ggplot 样式模拟 ggplot2 风格,ggplot2 是一个常用的 R 语言绘图包。
plt.style.use('ggplot')
customers = ['ABC','DEF','GHI','JKL','MNO']
customers_index = range(len(customers))
sale_amounts = [127,90,201,111,232]
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
ax1.bar(customers_index,sale_amounts,align='center',color='darkblue')
ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left')
plt.xticks(customers_index,customers,rotation=0,fontsize='small')
plt.xlabel('Customers_Name')
plt.ylabel('Sale Amount')
plt.title('Sale Amount per Customer')
#plt.savefig('bar_plot.png',dpi=400,bbox_inches='tight')
plt.show()

在这里插入图片描述

创建一个频率分布图

# 创建一个频率分布图
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('ggplot')
mu1, mu2, sigma = 100, 130, 15
x1 = mu1 + sigma*np.random.randn(10000)
x2 = mu2 + sigma*np.random.randn(10000)
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
n, bins, patches = ax1.hist(x1,bins=50,normed=False,color='darkgreen')
n, bins, patches = ax1.hist(x2,bins=50,normed=False,color='orange',alpha=0.5)
ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left')
plt.xlabel('Bins')
plt.ylabel('Number of Values in Bin')
fig.suptitle('Histograms',fontsize=14,fontweight='bold')
ax1.set_title('Two Frequency Distributions')
plt.savefig('histogram.png',dpi=400,bbox_inches='tight')
plt.show()

在这里插入图片描述

创建一个折线图

# 创建一幅折线图
import matplotlib.pyplot as plt
from numpy.random import randn
plt.style.use('ggplot')
plot_data1 = randn(50).cumsum()
plot_data2 = randn(50).cumsum()
plot_data3 = randn(50).cumsum()
plot_data4 = randn(50).cumsum()
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
# u/U:表示unicode字符串,不仅是中文, 可对任何字符串进行unicode编码
# r/R:非转义的原始字符串,如果以r开头,则说明后面的字符,都是普通的字符
ax1.plot(plot_data1,marker=r'o',color=u'blue',linestyle='-',label='Blue Solid')
ax1.plot(plot_data2,marker=r'+',color=u'red',linestyle='--',label='Red Dashed')
ax1.plot(plot_data3,marker=r'*',color=u'green',linestyle='-.',label='Green Dash Dot')
ax1.plot(plot_data4,marker=r's',color=u'orange',linestyle=':',label='Orange Dotted')
ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left')
ax1.set_title('Line Plots:Marker,Colors,and Linestyles')
plt.xlabel('Draw')
plt.ylabel('Random Number')
plt.legend(loc='best')
plt.savefig('line_plot.png',dpi=400,bbox_inches='tight')
plt.show()

在这里插入图片描述
创建一个散点图,并在各个点之间画一条回归曲线

# 创建一幅散点图,并在各个点之间画一条回归曲线
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
x = np.arange(start = 1.0, stop = 15.0, step = 1.0)
y_linear = x + 5.*np.random.randn(14)
y_quadratic = x**2 + 10.*np.random.randn(14)
# polyfit根据数据点拟合曲线; poly1d根据拟合的曲线参数生成方程
fn_linear = np.poly1d(np.polyfit(x,y_linear,deg = 1))
fn_quadratic = np.poly1d(np.polyfit(x,y_quadratic,deg = 2))
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
ax1.plot(x,y_linear,'bo',x,y_quadratic,'go',x,fn_linear(x),'b-',\
         x,fn_quadratic(x),'g-',linewidth=2.)
ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left')
ax1.set_title('Scatter Plots Regression Lines')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.xlim((min(x)-1.,max(x)+1.))
plt.ylim((min(y_quadratic)-10.,max(y_quadratic)+10.))
plt.savefig('scatter_plot.png',dpi=400,bbox_inches='tight')
plt.show()

在这里插入图片描述

创建一个箱线图:正态分布和对数正态分布数据的箱线图,以及这两个分布中抽样数据的箱线图

# 创建一幅箱线图:正态分布和对数正态分布数据的箱线图,以及这两个分布中抽样数据的箱线图
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
N = 500
normal = np.random.normal(loc=0.,scale=1.,size=N)
lognormal = np.random.lognormal(mean=0.,sigma=1.,size=N)
index_value = np.random.randint(low=0,high=N-1,size=N)
normal_sample = normal[index_value]
lognormal_sample = lognormal[index_value]
box_plot_data = [normal,normal_sample,lognormal,lognormal_sample]
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
box_labels = ['normal','normal_sample','lognormal','lognormal_sample']
# otch=False 表示箱体是矩形,而不是在中间收缩
# sym='.' 表示离群点使用圆点,而不是默认的 + 符号
# vert=True 表示箱体是垂直的,不是水平的
# whis=1.5 设定了直线从第一四分位数和第三四分位数延伸出的范围
ax1.boxplot(box_plot_data,notch=False,sym='.',vert=True,whis=1.5,\
            showmeans=True,labels=box_labels)
ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left')
ax1.set_title('Box Plots: Resampling of Two Distribution')
ax1.set_xlabel('Distribution')
ax1.set_ylabel('Value')
plt.show()

在这里插入图片描述

使用数据框中的数据创建一对条形图和箱线图,并将它们并排放置

# 使用数据框中的数据创建一对条形图和箱线图,并将它们并排放置
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
fig, axes = plt.subplots(nrows = 1, ncols = 2)
# ravel 函数将两个子图分别赋给两个变量ax1 和ax2
ax1, ax2 = axes.ravel()
'''
# 用 pd.DataFrame 创建一个数据表
Metrics     Metric 1  Metric 2  Metric 3
Customer 1  0.978255  0.126602  0.168026
Customer 2  0.933977  0.289068  0.604379
Customer 3  0.081579  0.122878  0.533946
Customer 4  0.602500  0.847248  0.324586
Customer 5  0.619023  0.521455  0.546729
'''
data_frame = pd.DataFrame(np.random.rand(5,3),\
             index=['Customer 1','Customer 2','Customer 3','Customer 4','Customer 5'],\
             columns=pd.Index(['Metric 1','Metric 2','Metric 3'],name='Metrics'))
data_frame.plot(kind='bar',ax=ax1,alpha=0.75,title='Bar Plot')
plt.setp(ax1.get_xticklabels(),rotation=45,fontsize=10)
plt.setp(ax1.get_yticklabels(),rotation=0,fontsize=10)
ax1.set_xlabel('Customer')
ax1.set_ylabel('Value')
ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left')
# 为箱线图创建一个颜色字典
colors = dict(boxes='DarkBlue',whiskers='Gray',medians='Red',caps='Black')
data_frame.plot(kind='box',color=colors,sym='r.',ax=ax2,title='Box Plot')
plt.setp(ax2.get_xticklabels(),rotation=45,fontsize=10)
plt.setp(ax2.get_yticklabels(),rotation=0,fontsize=10)
ax2.set_xlabel('Metric')
ax2.set_ylabel('Value')
ax2.xaxis.set_ticks_position('bottom')
ax2.yaxis.set_ticks_position('left')
plt.savefig('pandas_plots.png', dpi=400, bbox_inches='tight')
plt.show()

在这里插入图片描述

使用 ggplot 包进行数据统计图

# ggplot 创建基础统计图,使用 ggplot 包内部的数据
from ggplot import *
print(mtcars.head())
plt1 = ggplot(aes(x='mpg'),data=mtcars)+geom_histogram(fill='darkblue',binwidth=2)+xlim(10,35)+ylim(0,10)+xlab("MPG")+ylab("Frequency")+ggtitle("Histogram of MPG")
print(plt1)

在这里插入图片描述

print(diamonds.head())
plt3 = ggplot(diamonds, aes(x='carat', y='price', colour='cut')) +\
geom_point(alpha=0.5) +\
scale_color_gradient(low='#05D9F6', high='#5011D1') +\
xlim(0, 6) + ylim(0, 20000) +\
xlab("Carat") + ylab("Price") +\
ggtitle("Diamond Price by Carat and Cut") +\
theme_gray()
print(plt3)

在这里插入图片描述

采用更加高级的 seaborn 包创建数据统计图
创建各种统计图

# seaborn 创建各种统计图
import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pylab import savefig
sns.set(color_codes=True)
# 直方图
x = np.random.normal(size = 100)
sns.distplot(x,bins=20,kde=False,rug=True,label='Histogram w/o Density')
#sns.axlabel('Value','Frequency')
plt.title('Histogram of a Random Sample from a Normal Distribution')
plt.legend()
# 带有回归直线的散点图与单变量直方图
mean, cov = [5, 10],[(1, .5),(.5, 1)]
data = np.random.multivariate_normal(mean, cov, 200)
data_frame = pd.DataFrame(data, columns = ['x','y'])
sns.jointplot(x='x',y='y',data=data_frame,kind='reg').set_axis_labels('x','y')
plt.suptitle('Joint Plot of Two Variables with Bivariate and Univariate Graphs')
# 成对变量之间的散点图与单变量直方图
iris = sns.load_dataset('iris')
sns.pairplot(iris)
# 按照某几个变量生成的箱线图
tips = sns.load_dataset('tips')
sns.factorplot(x='time',y='total_bill',hue='smoker',col='day',data=tips,\
               kind='box',size=4,aspect=0.5)
# 带有bootstrap置信区间的线性回归模型
sns.lmplot(x='total_bill',y='tip',data=tips)
# 带有bootstrap置信区间的逻辑斯蒂回归模型
tips["big_tip"] = (tips.tip / tips.total_bill) > .15
sns.lmplot(x="total_bill", y="big_tip", data=tips, logistic=True, y_jitter=.03)
plt.title("Logistic Regression of Big Tip vs. Total Bill")
plt.show()
savefig("seaborn_plots.png")

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/sinat_41842926/article/details/84971284