matplotlib 画图基本种类

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

plt.rcParams['font.sans-serif'] = ['SimHei'] #设置中文字体
plt.rcParams['axes.unicode_minus'] = False ##设置负号显示正常
#设置坐标轴的范围
#plt.xlim()
#plt.xticks(())#忽略xticks
#plt.ylim()
#plt.yticks(())#忽略yticks

一、散点图

data = pd.read_excel(r'C:\Users\admin\Desktop\C-D生产函数.xlsx')
#scatter画散点图 size=75  透明度为50% 利用xticks函数来隐藏x坐标轴
plt.scatter(data['K'],data['Y'])
plt.xlabel('K',size = 15)
plt.ylabel('L',size = 15)
plt.title('K与L之间的散点图',size = 20)
sns.regplot(data['K'],data['Y']) ##添加趋势线
plt.show()

 

 

 二、雷达图

course = ['C++','Python','高等数学','大学英语','软件工程','组成原理','操作系统','网络工程']
scores = [92,75,85,69,85,84,86,76]
dataLength = len(scores)

# 把园等分为dataLength份
angles = np.linspace(0,2*np.pi,dataLength,endpoint=False)
scores.append(scores[0])
angles = np.append(angles,angles[0])
plt.polar(angles,scores,'b.-',lw=2,alpha = 0.3)
plt.thetagrids(angles*180/np.pi,course,fontproperties = 'simhei')
plt.fill(angles,scores,facecolor='g',alpha = 0.2)
plt.show()

 

 

 三、箱线图

data = pd.read_excel(r'C:\Users\admin\Desktop\C-D生产函数.xlsx')
y1 = data.iloc[:,1]
y2 = data.iloc[:,2]
plt.boxplot([y1,y2],labels = [y1.name,y2.name])    
plt.title('箱线图')
plt.show()

 

 

 四、折线图

data = pd.read_excel(r'C:\Users\admin\Desktop\C-D生产函数.xlsx')
data.head()
x = data.iloc[:,0]
x_ticks = range(0,len(x),5)
x.iloc[x_ticks]
y1 = data.iloc[:,1]
y2 = data.iloc[:,2]
y3 = data.iloc[:,3]
plt.plot(y1,label = y1.name,marker = '.')
plt.plot(y2,label = y2.name,marker = '+')
plt.plot(y3,label = y3.name,marker = '*',ms = 4)
plt.xticks(ticks = x_ticks,labels = x.iloc[x_ticks])
#plt.xlabel('')
#plt.ylabel('')
plt.title('折线图')
##添加数据标签
'''
for y in [y1, y2, y3]:
    for x1, yy in zip(x, y):
        plt.text(x1, yy + 1, str(yy), ha='center', va='bottom', fontsize=20, rotation=0)
'''
plt.legend(loc = 'best')
plt.show()

 

 五、条形图

(1)堆积条形图

##堆积条形图
fig = plt.figure();ax = fig.add_subplot(1,1,1)
data = pd.read_excel(r'C:\Users\admin\Desktop\C-D生产函数.xlsx')
x = data.iloc[:,0]
y1 = data.iloc[:,1]
y2 = data.iloc[:,2]
y3 = data.iloc[:,3]
ticks = ax.set_xticks(x.iloc[0::5])
labels = ax.set_xticklabels(x.iloc[0::5])
plt.bar(x,height=y1,label = y1.name, width=0.4, alpha=0.8)
plt.bar(x,height=y2,label = y2.name, width=0.4, alpha=0.8)
plt.bar(x,height=y3,label = y3.name, width=0.4, alpha=0.8)
#plt.xticks(ticks = x.iloc[0::5],labels = x.iloc[0::5])
plt.legend(loc = 'best')
#添加数据标签
'''
for y in [y1, y2, y3]:
    for x1, yy in zip(x, y):
        plt.text(x1, yy + 1, str(yy), ha='center', va='bottom', fontsize=20, rotation=0)
'''

plt.title('堆积条形图')
plt.show()
堆积条形图

 

 (2)多组条形图

fig = plt.figure();ax = fig.add_subplot(1,1,1)
data = pd.read_excel(r'C:\Users\admin\Desktop\C-D生产函数.xlsx')
bar_width = 0.3
'''
total_width, n = 0.9, 3     # 有多少个类型,只需更改n即可
bar_width = total_width / n
'''
x = data.iloc[:,0]
y1 = data.iloc[:,1]
y2 = data.iloc[:,2]
y3 = data.iloc[:,3]
plt.bar(x = range(len(x)),height=y1,label = y1.name,
        alpha=0.8,width = bar_width)
plt.bar(x= np.arange(len(x))+bar_width,height=y2,label = y2.name,
        alpha=0.8,width = bar_width)
plt.bar(x = np.arange(len(x))+2*bar_width,height=y3,label = y3.name,
        width=bar_width, alpha=0.8)
ticks = ax.set_xticks(range(0,len(x),5))
labels = ax.set_xticklabels(x.iloc[0::5])
plt.legend(loc = 'best')
'''
for a, b in zip(x,y1):
    plt.text(a, b+1, str(b), ha='center', va='bottom')
for a,b in zip(x,y2):
    plt.text(a+bar_width, b+0.1, str(b), ha='center', va='bottom')
for a,b in zip(x, y3):
    plt.text(a+2*bar_width, b+0.1, b, ha='center', va='bottom')
'''
plt.title('条形图')
plt.show()
多组条形图

 

 (3)条形图上添加折线图

##折线图和柱状图组合
data = pd.read_excel(r'C:\Users\admin\Desktop\C-D生产函数.xlsx')
x = data.iloc[:5,0]
y1 = data.iloc[:5,1]
plt.bar(x,height=y1,label = y1.name, width=0.4, alpha=0.8)
plt.legend(loc = 'best')
#添加数据标签
'''
for x1,yy in zip(x, y1):
   plt.text(x1, yy + 1, str(yy), ha='center', va='bottom', fontsize=20, rotation=0)
'''
plt.plot(x,y1,label = y1.name,marker = '*',color = 'green')
plt.title('组合图')
plt.show()
组合

 

 六、直方图

##直方图
plt.rcParams['font.sans-serif'] = ['SimHei'] #设置中文字体
plt.rcParams['axes.unicode_minus'] = False ##设置负号显示正常
plt.hist(np.random.randn(10000),bins=20,edgecolor="black",alpha=0.8)
plt.xlabel("区间")
plt.ylabel("频数/频率")
plt.title('直方图')
plt.show()

 

 七、饼图

piedata= pd.read_excel(r'E:\学习数据\饼图数据.xlsx')
plt.axes(aspect='equal')                       
plt.xlim(0,8)
plt.ylim(0,8)
#不显示边框
plt.gca().spines['right'].set_color('none')
plt.gca().spines['top'].set_color('none')
plt.gca().spines['left'].set_color('none')
plt.gca().spines['bottom'].set_color('none')
explode=[0,0,0.2,0]

plt.pie(x=piedata.iloc[:,2], #绘制数据
labels=piedata.iloc[:,0],#添加编程语言标签
explode=explode,#突出显示Python
colors=['pink','lightskyblue','orchid','burlywood'], #设置自定义填充色
autopct='%.2f%%',#设置百分比的格式,保留3位小数
pctdistance=0.6, #设置百分比标签和圆心的距离
startangle=180,#设置饼图的初始角度
counterclock= False,#是否为逆时针方向,False表示顺时针方向
#wedgeprops= {'linewidth':1,'edgecolor':'green'},#设置饼图内外边界的属性值
textprops= {'fontsize':12,'color':'black'},#设置文本标签的属性值
frame=0) #是否显示饼图的圆圈,1为显示
plt.title('饼图')
plt.show()
饼图

 

 八、对不同区域的值使用不同颜色

对于销量在5以下:绿色

销量在5-10之间:天蓝色

销量在10-15之间:金黄色

销量在15以上:珊瑚色

##对不同区域的值适用不同颜色
x=[1,2,3,4,5,6,7,8,9,10,11,12]
y=[6,3,9,2,6,16,8,10,4,14,18,6]

def get_color(x, y):
    """对销量不同的区段标为不同的颜色"""
    color = []
    for i in range(len(x)):

        if y[i] < 5:
            color.append("green")
        elif y[i] < 10:
            color.append("lightseagreen")
        elif y[i] < 15:
            color.append("gold")
        else:
            color.append("coral")

    return color

plt.bar(x,y,label="销量",color=get_color(x,y), tick_label=x)

for a,b in zip(x, y):
    plt.text(a, b+0.1, b, ha='center', va='bottom')

plt.legend(loc="upper left")
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.ylabel('销量')
plt.xlabel('date')
plt.title("月份销量的分布情况")
plt.show()
View Code

 

posted @ 2020-08-01 19:11  pumpkin_J  阅读(571)  评论(0)    收藏  举报