matplotlib 画统计图大全

2019-03-26  本文已影响0人  一百万个不确定

matplotlib 画统计图大全

  1. 柱状图
  1. 堆积柱状图
  1. 条形图(横向柱状图)
"""
Simple demo of a horizontal bar chart.
"""
import matplotlib.pyplot as plt
plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt

# Example data
people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
y_pos = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people))
error = np.random.rand(len(people))

plt.barh(y_pos, performance, xerr=error, align='center', alpha=0.4)
plt.yticks(y_pos, people)
plt.xlabel('Performance')
plt.title('How fast do you want to go today?')
plt.show()

3.png
  1. 折线图
import sys

import matplotlib.pyplot as plt
import tushare as ts


# 获取上证50指数的历史数据
data = ts.get_hist_data('sz50',start='2018-11-01',end='2019-03-25')

data = data.sort_index()

# 一个基本的折线图
x = range(len(data))
# 收盘价的折线图
plt.plot(x,data['close'])
plt.show()
4.png
  1. 数据地图
import requests
from csv import DictReader
DATA_URL = 'http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_month.csv'
print("Downloading", DATA_URL)
resp = requests.get(DATA_URL)
quakes = list(DictReader(resp.text.splitlines()))
# ...avoiding numpy/pandas Array() for now, and can't care enough to do this less awkwardly...
lngs = [float(q['longitude']) for q in quakes]
lats = [float(q['latitude']) for q in quakes]
mags = [2 ** float(q['mag']) for q in quakes]

# %matplotlib  # in iPython
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
plt.figure(figsize=(14, 8))
earth = Basemap()
earth.bluemarble(alpha=0.42)
earth.drawcoastlines(color='#555566', linewidth=1)
plt.scatter(lngs, lats, mags, 
            c='red',alpha=0.5, zorder=10)
plt.xlabel("M4.5 earthquakes in the past 30 days from March 18, 2016 (USGS)")
plt.savefig('usgs-4.5quakes-bluemarble.png', dpi=350)

plt.savefig('usgs-4.5quakes.svg')

fig, ax = plt.subplots()
earth = Basemap(ax=ax)
earth.drawcoastlines(color='#555566', linewidth=1)
ax.scatter(lngs, lats, mags, c='red',alpha=0.5, zorder=10)
ax.set_xlabel("Hello there")
fig.savefig('hello-ax.png')

import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap


DATA_URL = 'http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_month.csv'
print("Downloading", DATA_URL)
df = pd.read_csv(DATA_URL)

fig, ax = plt.subplots()
earth = Basemap(ax=ax)
earth.drawcoastlines(color='#556655', linewidth=0.5)
ax.scatter(df['longitude'], df['latitude'], df['mag'] ** 2, 
           c='red', alpha=0.5, zorder=10)
ax.set_xlabel("This month's 4.5M+ earthquakes")
fig.savefig('usgs-monthly-4.5M.png')
real5.png
  1. 饼图(环图)
import matplotlib.pyplot as plt

# Pie chart, where the slices will be ordered and plotted counter-clockwise:
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')

fig1, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
        shadow=True, startangle=90)
ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

plt.savefig('Demo_official.jpg')
plt.show()
5.png
  1. 雷达图
  1. 漏斗图
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib.offsetbox import (TextArea, DrawingArea, OffsetImage,
                                  AnnotationBbox)
from matplotlib.cbook import get_sample_data

#中文及负号处理
plt.rcParams['font.sans-serif'] = 'Microsoft YaHei'
plt.rcParams['axes.unicode_minus'] = False

N = 5
width = 0.55
x1 = np.array([1000, 500, 300, 200,150])
x2= np.array((x1.max()-x1)/2) # 占位
#x1+x2
x3=[]
for i,j in zip(x1,x2):
    x3.append(i+j)
x3 = np.array(x3)


y = -np.sort(-np.arange(N)) # 倒转y轴
labels=['浏览商品','放入购物车','生成订单','支付订单','完成交易']

#figure
fig = plt.figure(figsize=(12,8))
ax = fig.add_subplot(111)

#plot
ax.barh(y,x3,width,tick_label=labels,color='r',alpha=0.85)
ax.plot(x3,y,'red',alpha=0.7)
ax.barh(y,x2,width,color='w',alpha =1) #辅助图
ax.plot(x2,y,'red',alpha=0.7)

#setting
transform = []       
for i in range(0,len(x1)):
    if i < len(x1)-1:
        transform.append('%.2f%%'%((x1[i+1]/x1[i])*100))
l = [(500,3),(500,2),(500, 1),(500, 0)]
for a,b in zip(transform,l):
    offsetbox = TextArea(a, minimumdescent=False)
    ab = AnnotationBbox(offsetbox, b,
                        xybox=(0, 40),
                        boxcoords="offset points",
                        arrowprops=dict(arrowstyle="->"))
    ax.add_artist(ab)
ax.set_xticks([0,1000])
ax.set_yticks(y)

plt.show()
7.png
  1. 散点图
8.png
上一篇下一篇

猜你喜欢

热点阅读