Python-Matplotlib

介绍

matplotlib是一个 Python 的 2D绘图库,它以各种硬拷贝格式和跨平台的交互式环境生成出版质量级别的图形。

简单应用

引入包

  1. import numpy as np  
  2. import matplotlib.pyplot as plt 
import pandas as pd
unrate = pd.read_csv('UNRATE.csv')
unrate['DATE'] = pd.to_datetime(unrate['DATE'])#按照标准的时间格式输出

print (unrate.head((12)))#前12个值

import matplotlib.pyplot as plt
plt.plot()#画图操作

plt.show()#显示

first_twelve = unrate[0:12]
plt.plot(first_twelve['DATE'],first_twelve['VALUE'])#第一个'DATE'为横坐标,另一个为纵坐标

plt.show()


plt.plot(first_twelve['DATE'],first_twelve['VALUE'])#第一个'DATE'为横坐标,另一个为纵坐标
plt.xticks(rotation=45)#指定角度旋转

plt.show()

plt.plot(first_twelve['DATE'],first_twelve['VALUE'])#第一个'DATE'为横坐标,另一个为纵坐标
plt.xticks(rotation=90)#指定角度旋转
plt.xlabel('Month')#x轴上显示Month
plt.ylabel('Unemployment Rate')#在y轴上显示
plt.title('Monthly Unemployment Trends, 1948')#主题

plt.show()


#画图
import matplotlib.pyplot as plt
fig = plt.figure()#指定默认画图的区间
#加入三个子图
ax1 = fig.add_subplot(2,2,1)#第一个子图2*2当中的第一个模块
ax2 = fig.add_subplot(2,2,2)#第二个子图2*2当中的第二个模块
ax3 = fig.add_subplot(2,2,4)#第三个子图2*2当中的第四个模块
#第三个模块不会画出来

plt.show()


#折线图  不指定默认区域
import numpy as np
fig = plt.figure(figsize=(3,3))#当前画图与的长度*3.当前画图域宽度为3
ax1 = fig.add_subplot(2,1,1)
ax2 = fig.add_subplot(2,1,2)


ax1.plot(np.random.randint(1,5,5), np.arange(5))#随机画的东西
ax2.plot(np.arange(10)*3,np.arange(10))

plt.show()


#同一个人图画两条折线
import pandas as pd
unrate = pd.read_csv('UNRATE.csv')
unrate['DATE'] = pd.to_datetime(unrate['DATE'])#按照标准的时间格式输出
unrate['MONTH'] = unrate['DATE'].dt.month
unrate['MONTH'] = unrate['DATE'].dt.month
fig = plt.figure(figsize=(6,3))


plt.plot(unrate[0:12]['MONTH'], unrate[0:12]['VALUE'],c='red')

plt.plot(unrate[12:24]['MONTH'], unrate[12:24]['VALUE'],c='blue')

plt.show()



#例子:把每年浮动情况画出来,到右上角画出一个大方块
fig = plt.figure(figsize=(10,6))
colors = ['red','blue','green','orange','black']
for i in range(5):
    start_index = i*12
    end_index = (i+1)*12
    subset = unrate[start_index:end_index]
    label = str(1948 + i)
    plt.plot(subset['MONTH'], subset['VALUE'], c=colors[i], label=label)
plt.legend(loc='best')#定位当前框(默认右上角)


plt.show()


#柱状图
import matplotlib.pyplot as plt
from numpy import arange
#The Axes.bar() method has 2 required parameters, left and height. 
#We use the left parameter to specify the x coordinates of the left sides of the bar. 
#We use the height parameter to specify the height of each bar
#选择评分指标,拿出这些列
num_cols = ['RT_user_norm', 'Metacritic_user_nom', 'IMDB_norm', 'Fandango_Ratingvalue', 'Fandango_Stars']


bar_heights = norm_reviews.ix[0, num_cols].values#当前柱的高度
#print bar_heights#打印媒体评分值
bar_positions = arange(5) + 0.75#柱离原点的距离
#print (bar_positions)
fig, ax = plt.subplots()#把图拿出来,ax实际画图得到的轴,fig控制图长什么样子
ax.bar(bar_positions, bar_heights, 0.5)#bar形图 0.5-定义柱的宽度

plt.show()


#横柱图
import matplotlib.pyplot as plt
from numpy import arange
num_cols = ['RT_user_norm', 'Metacritic_user_nom', 'IMDB_norm', 'Fandango_Ratingvalue', 'Fandango_Stars']


bar_widths = norm_reviews.ix[0, num_cols].values
bar_positions = arange(5) + 0.75
tick_positions = range(1,6)
fig, ax = plt.subplots()
ax.barh(bar_positions, bar_widths, 0.5)#barh横着画,bar竖着画


ax.set_yticks(tick_positions)
ax.set_yticklabels(num_cols)
ax.set_ylabel('Rating Source')
ax.set_xlabel('Average Rating')
ax.set_title('Average User Rating For Avengers: Age of Ultron (2015)')

plt.show()


#Let's look at a plot that can help us visualize many points.
#scatter散点图-横轴表示评分,横轴表示一个评分纵轴表示另一个评分
fig, ax = plt.subplots()
ax.scatter(norm_reviews['Fandango_Ratingvalue'], norm_reviews['RT_user_norm'])
ax.set_xlabel('Fandango')
ax.set_ylabel('Rotten Tomatoes')

plt.show()


#Color颜色
import pandas as pd
import matplotlib.pyplot as plt


women_degrees = pd.read_csv('percent-bachelors-degrees-women-usa.csv')
major_cats = ['Biology', 'Computer Science', 'Engineering', 'Math and Statistics']




cb_dark_blue = (0/255, 107/255, 164/255)#三原色,得到元组
cb_orange = (255/255, 128/255, 14/255)


fig = plt.figure(figsize=(12, 12))


for sp in range(0,4):
    ax = fig.add_subplot(2,2,sp+1)
    # The color for each line is assigned here.
    ax.plot(women_degrees['Year'], women_degrees[major_cats[sp]], c=cb_dark_blue, label='Women')
    ax.plot(women_degrees['Year'], 100-women_degrees[major_cats[sp]], c=cb_orange, label='Men')
    for key,spine in ax.spines.items():
        spine.set_visible(False)
    ax.set_xlim(1968, 2011)
    ax.set_ylim(0,100)
    ax.set_title(major_cats[sp])
    ax.tick_params(bottom="off", top="off", left="off", right="off")


plt.legend(loc='upper right')

plt.show()



猜你喜欢

转载自blog.csdn.net/qq_27262727/article/details/79571714
今日推荐