前言
數(shù)據(jù)可視化的第三方庫(kù)挺多的,這里我主要推薦三個(gè)摹察,分別是 Pygal恩掷、Bokeh、Plotly供嚎,廢話不多說黄娘,直接上~~
推薦
數(shù)據(jù)可視化的庫(kù)有挺多的,這里推薦幾個(gè)比較常用的:
Matplotlib
Pygal
Bokeh
Seaborn
Ggplot
Plotly
Pyechart
Pygal
pygal官網(wǎng)地址(http://www.pygal.org/en/stable/)
安裝pygal模塊
pygal模塊的安裝非常簡(jiǎn)單克滴,只需輸入一行pip命令即可
1 pip install pygal
安裝完成:
pygal模塊介紹
pygal是Python的第三方庫(kù)逼争,他的主要功能就是數(shù)據(jù)可視化,即將數(shù)字轉(zhuǎn)化成圖表的形式來呈現(xiàn)劝赔,它提供的圖表樣式有柱狀圖誓焦、折線圖、餅狀圖着帽、雷達(dá)圖......
柱狀圖
單列柱狀圖
import pygal
view = pygal.Bar()
#圖表名
view.title = '柱狀圖'
#添加數(shù)據(jù)
view.add('numbers', [0,2,4,6,8,10])
#在瀏覽器中查看
#view.render_in_browser()
#保存為view.svg(也可以保存為jpg)
view.render_to_file('view.svg')
效果圖:
注意:svg圖片用系統(tǒng)自帶的圖片查看器打開可能會(huì)顯示全黑色杂伟,可以嘗試使用Google瀏覽器打開
多列柱狀圖
#添加數(shù)據(jù)
view.add('numbers', [0,2,4,6,8,10])
view.add('numbers_2', [0,1,3,5,7,9])
堆疊柱狀圖
view = pygal.StackedBar()
橫向柱狀圖
view = pygal.HorizontalStackedBar()
折線圖
簡(jiǎn)單折線圖
import pygal
view = pygal.Line()
#圖表名
view.title = '折線圖'
#添加數(shù)據(jù)
view.add('numbers', [0,2,4,6,8,10])
view.add('numbers_2', [0,1,3,5,7,9])
#在瀏覽器中查看
#view.render_in_browser()
#保存為view.svg(也可以保存為jpg)
view.render_to_file('view.svg')
效果圖:
縱向折線圖
view = pygal.HorizontalLine()
堆疊折線圖
view = pygal.StackedLine(fill=True)
餅狀圖
簡(jiǎn)單餅狀圖
import pygal
view = pygal.Pie()
#圖表名
view.title = '餅狀圖'
#添加數(shù)據(jù)
view.add('A', 31)
view.add('B', 55)
view.add('C', 14)
#保存為view.svg(也可以保存為jpg)
view.render_to_file('view.svg')
效果圖:
多級(jí)餅狀圖
#添加數(shù)據(jù)
view.add('A', [31,25])
view.add('B', [55,38])
view.add('C', [14,37])
圓環(huán)圖
#設(shè)置空心圓半徑
view = pygal.Pie(inner_radius=0.4)
半圓圖
view = pygal.Pie(half_pie=True)
雷達(dá)圖
基礎(chǔ)雷達(dá)圖
import pygal
view = pygal.Radar()
#圖表名
view.title = '雷達(dá)圖'
#添加數(shù)據(jù)(可以為任意個(gè))
view.add('A', [31,56,34,67,34])
view.add('B', [23,18,57,45,35])
view.add('C', [14,45,76,34,76])
#保存為view.svg(也可以保存為jpg)
view.render_to_file('view.svg')
效果圖:
plotly
plotly 文檔地址(https://plot.ly/python/#financial-charts)
Plotly 是一款用來做數(shù)據(jù)分析和可視化的在線平臺(tái)移层,功能非常強(qiáng)大,可以在線繪制很多圖形比如條形圖、散點(diǎn)圖赫粥、餅圖观话、直方圖等等。而且還是支持在線編輯越平,以及多種語言python频蛔、javascript、matlab秦叛、R等許多API晦溪。它在python中使用也很簡(jiǎn)單,直接用pip install plotly就可以了书闸。推薦最好在jupyter notebook中使用,pycharm操作不是很方便利凑。使用Plotly可以畫出很多媲美Tableau的高質(zhì)量圖:
這里嘗試做了折線圖浆劲、散點(diǎn)圖和直方圖,代碼如下:
首先導(dǎo)入庫(kù)
from plotly.graph_objs import Scatter,Layout
import plotly
import plotly.offline as py
import numpy as np
import plotly.graph_objs as go
#setting offilne
plotly.offline.init_notebook_mode(connected=True)
上面幾行代碼主要是引用一些庫(kù)哀澈,plotly有在線和離線兩種模式牌借,在線模式需要有賬號(hào)可以云編輯。我選用的離線模式割按,plotly設(shè)置為offline模式就可以直接在notebook里面顯示了膨报。
1.制作折線圖
N = 100
random_x = np.linspace(0,1,N)
random_y0 = np.random.randn(N)+5
random_y1 = np.random.randn(N)
random_y2 = np.random.randn(N)-5
#Create traces
trace0 = go.Scatter(
x = random_x,
y = random_y0,
mode = 'markers',
name = 'markers'
)
trace1 = go.Scatter(
x = random_x,
y = random_y1,
mode = 'lines+markers',
name = 'lines+markers'
)
trace2 = go.Scatter(
x = random_x,
y = random_y2,
mode = 'lines',
name = 'lines'
)
data = [trace0,trace1,trace2]
py.iplot(data)
隨機(jī)設(shè)置4個(gè)參數(shù),一個(gè)x軸的數(shù)字和三個(gè)y軸的隨機(jī)數(shù)據(jù)适荣,制作出三種不同類型的圖现柠。trace0是markers,trace1是lines和markers,trace3是lines弛矛。然后把三種圖放在data這個(gè)列表里面够吩,調(diào)用py.iplot(data)即可。
繪制的圖片系統(tǒng)默認(rèn)配色也挺好看的~
2.制作散點(diǎn)圖
trace1 = go.Scatter(
y = np.random.randn(500),
mode = 'markers',
marker = dict(
size = 16,
color = np.random.randn(500),
colorscale = 'Viridis',
showscale = True
)
)
data = [trace1]
py.iplot(data)
把mode設(shè)置為markers就是散點(diǎn)圖丈氓,然后marker里面設(shè)置一組參數(shù)周循,比如顏色的隨機(jī)范圍,散點(diǎn)的大小万俗,還有圖例等等湾笛。
3.直方圖
trace0 = go.Bar(
x = ['Jan','Feb','Mar','Apr', 'May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'],
y = [20,14,25,16,18,22,19,15,12,16,14,17],
name = 'Primary Product',
marker=dict(
color = 'rgb(49,130,189)'
)
)
trace1 = go.Bar(
x = ['Jan','Feb','Mar','Apr', 'May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'],
y = [19,14,22,14,16,19,15,14,10,12,12,16],
name = 'Secondary Product',
marker=dict(
color = 'rgb(204,204,204)'
)
)
data = [trace0,trace1]
py.iplot(data)
Bokeh
條形圖
這配色看著還挺舒服的,比 pyecharts 條形圖的配色好看一點(diǎn)闰歪。
from bokeh.io import show, output_file
from bokeh.models import ColumnDataSource
from bokeh.palettes import Spectral6
from bokeh.plotting import figure
output_file("colormapped_bars.html")# 配置輸出文件名
fruits = ['Apples', '魅族', 'OPPO', 'VIVO', '小米', '華為'] # 數(shù)據(jù)
counts = [5, 3, 4, 2, 4, 6] # 數(shù)據(jù)
source = ColumnDataSource(data=dict(fruits=fruits, counts=counts, color=Spectral6))
p = figure(x_range=fruits, y_range=(0,9), plot_height=250, title="Fruit Counts",
toolbar_location=None, tools="")# 條形圖配置項(xiàng)
p.vbar(x='fruits', top='counts', width=0.9, color='color', legend="fruits", source=source)
p.xgrid.grid_line_color = None # 配置網(wǎng)格線顏色
p.legend.orientation = "horizontal" # 圖表方向?yàn)樗椒较?p.legend.location = "top_center"
show(p) # 展示圖表
年度條形圖
可以對(duì)比不同時(shí)間點(diǎn)的量嚎研。
from bokeh.io import show, output_file
from bokeh.models import ColumnDataSource, FactorRange
from bokeh.plotting import figure
output_file("bars.html") # 輸出文件名
fruits = ['Apple', '魅族', 'OPPO', 'VIVO', '小米', '華為'] # 參數(shù)
years = ['2015', '2016', '2017'] # 參數(shù)
data = {'fruits': fruits,
'2015': [2, 1, 4, 3, 2, 4],
'2016': [5, 3, 3, 2, 4, 6],
'2017': [3, 2, 4, 4, 5, 3]}
x = [(fruit, year) for fruit in fruits for year in years]
counts = sum(zip(data['2015'], data['2016'], data['2017']), ())
source = ColumnDataSource(data=dict(x=x, counts=counts))
p = figure(x_range=FactorRange(*x), plot_height=250, title="Fruit Counts by Year",
toolbar_location=None, tools="")
p.vbar(x='x', top='counts', width=0.9, source=source)
p.y_range.start = 0
p.x_range.range_padding = 0.1
p.xaxis.major_label_orientation = 1
p.xgrid.grid_line_color = None
show(p)
餅圖
from collections import Counter
from math import pi
import pandas as pd
from bokeh.io import output_file, show
from bokeh.palettes import Category20c
from bokeh.plotting import figure
from bokeh.transform import cumsum
output_file("pie.html")
x = Counter({
'中國(guó)': 157,
'美國(guó)': 93,
'日本': 89,
'巴西': 63,
'德國(guó)': 44,
'印度': 42,
'意大利': 40,
'澳大利亞': 35,
'法國(guó)': 31,
'西班牙': 29
})
data = pd.DataFrame.from_dict(dict(x), orient='index').reset_index().rename(index=str, columns={0:'value', 'index':'country'})
data['angle'] = data['value']/sum(x.values()) * 2*pi
data['color'] = Category20c[len(x)]
p = figure(plot_height=350, title="Pie Chart", toolbar_location=None,
tools="hover", tooltips="@country: @value")
p.wedge(x=0, y=1, radius=0.4,
start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'),
line_color="white", fill_color='color', legend='country', source=data)
p.axis.axis_label=None
p.axis.visible=False
p.grid.grid_line_color = None
show(p)
條形圖
from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource
from bokeh.palettes import GnBu3, OrRd3
from bokeh.plotting import figure
output_file("stacked_split.html")
fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
years = ["2015", "2016", "2017"]
exports = {'fruits': fruits,
'2015': [2, 1, 4, 3, 2, 4],
'2016': [5, 3, 4, 2, 4, 6],
'2017': [3, 2, 4, 4, 5, 3]}
imports = {'fruits': fruits,
'2015': [-1, 0, -1, -3, -2, -1],
'2016': [-2, -1, -3, -1, -2, -2],
'2017': [-1, -2, -1, 0, -2, -2]}
p = figure(y_range=fruits, plot_height=250, x_range=(-16, 16), title="Fruit import/export, by year",
toolbar_location=None)
p.hbar_stack(years, y='fruits', height=0.9, color=GnBu3, source=ColumnDataSource(exports),
legend=["%s exports" % x for x in years])
p.hbar_stack(years, y='fruits', height=0.9, color=OrRd3, source=ColumnDataSource(imports),
legend=["%s imports" % x for x in years])
p.y_range.range_padding = 0.1
p.ygrid.grid_line_color = None
p.legend.location = "top_left"
p.axis.minor_tick_line_color = None
p.outline_line_color = None
show(p)
散點(diǎn)圖
from bokeh.plotting import figure, output_file, show
output_file("line.html")
p = figure(plot_width=400, plot_height=400)
p.circle([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], size=20, color="navy", alpha=0.5)
show(p)
六邊形圖
這兩天,馬蜂窩剛被發(fā)現(xiàn)數(shù)據(jù)造假库倘,這不嘉赎,與馬蜂窩應(yīng)應(yīng)景置媳。
import numpy as np
from bokeh.io import output_file, show
from bokeh.plotting import figure
from bokeh.util.hex import axial_to_cartesian
output_file("hex_coords.html")
q = np.array([0, 0, 0, -1, -1, 1, 1])
r = np.array([0, -1, 1, 0, 1, -1, 0])
p = figure(plot_width=400, plot_height=400, toolbar_location=None) #
p.grid.visible = False # 配置網(wǎng)格是否可見
p.hex_tile(q, r, size=1, fill_color=["firebrick"] * 3 + ["navy"] * 4,
line_color="white", alpha=0.5)
x, y = axial_to_cartesian(q, r, 1, "pointytop")
p.text(x, y, text=["(%d, %d)" % (q, r) for (q, r) in zip(q, r)],
text_baseline="middle", text_align="center")
show(p)
環(huán)比條形圖
這個(gè)實(shí)現(xiàn)挺厲害的,看了一眼就吸引了我公条。我在代碼中都做了一些注釋拇囊,希望對(duì)你理解有幫助。注:圓心為正中央靶橱,即直角坐標(biāo)系中標(biāo)簽為(0寥袭,0)的地方。
from collections import OrderedDict
from math import log, sqrt
import numpy as np
import pandas as pd
from six.moves import cStringIO as StringIO
from bokeh.plotting import figure, show, output_file
antibiotics = """
bacteria, penicillin, streptomycin, neomycin, gram
結(jié)核分枝桿菌, 800, 5, 2, negative
沙門氏菌, 10, 0.8, 0.09, negative
變形桿菌, 3, 0.1, 0.1, negative
肺炎克雷伯氏菌, 850, 1.2, 1, negative
布魯氏菌, 1, 2, 0.02, negative
銅綠假單胞菌, 850, 2, 0.4, negative
大腸桿菌, 100, 0.4, 0.1, negative
產(chǎn)氣桿菌, 870, 1, 1.6, negative
白色葡萄球菌, 0.007, 0.1, 0.001, positive
溶血性鏈球菌, 0.001, 14, 10, positive
草綠色鏈球菌, 0.005, 10, 40, positive
肺炎雙球菌, 0.005, 11, 10, positive
"""
drug_color = OrderedDict([# 配置中間標(biāo)簽名稱與顏色
("盤尼西林", "#0d3362"),
("鏈霉素", "#c64737"),
("新霉素", "black"),
])
gram_color = {
"positive": "#aeaeb8",
"negative": "#e69584",
}
# 讀取數(shù)據(jù)
df = pd.read_csv(StringIO(antibiotics),
skiprows=1,
skipinitialspace=True,
engine='python')
width = 800
height = 800
inner_radius = 90
outer_radius = 300 - 10
minr = sqrt(log(.001 * 1E4))
maxr = sqrt(log(1000 * 1E4))
a = (outer_radius - inner_radius) / (minr - maxr)
b = inner_radius - a * maxr
def rad(mic):
return a * np.sqrt(np.log(mic * 1E4)) + b
big_angle = 2.0 * np.pi / (len(df) + 1)
small_angle = big_angle / 7
# 整體配置
p = figure(plot_width=width, plot_height=height, title="",
x_axis_type=None, y_axis_type=None,
x_range=(-420, 420), y_range=(-420, 420),
min_border=0, outline_line_color="black",
background_fill_color="#f0e1d2")
p.xgrid.grid_line_color = None
p.ygrid.grid_line_color = None
# annular wedges
angles = np.pi / 2 - big_angle / 2 - df.index.to_series() * big_angle #計(jì)算角度
colors = [gram_color[gram] for gram in df.gram] # 配置顏色
p.annular_wedge(
0, 0, inner_radius, outer_radius, -big_angle + angles, angles, color=colors,
)
# small wedges
p.annular_wedge(0, 0, inner_radius, rad(df.penicillin),
-big_angle + angles + 5 * small_angle, -big_angle + angles + 6 * small_angle,
color=drug_color['盤尼西林'])
p.annular_wedge(0, 0, inner_radius, rad(df.streptomycin),
-big_angle + angles + 3 * small_angle, -big_angle + angles + 4 * small_angle,
color=drug_color['鏈霉素'])
p.annular_wedge(0, 0, inner_radius, rad(df.neomycin),
-big_angle + angles + 1 * small_angle, -big_angle + angles + 2 * small_angle,
color=drug_color['新霉素'])
# 繪制大圓和標(biāo)簽
labels = np.power(10.0, np.arange(-3, 4))
radii = a * np.sqrt(np.log(labels * 1E4)) + b
p.circle(0, 0, radius=radii, fill_color=None, line_color="white")
p.text(0, radii[:-1], [str(r) for r in labels[:-1]],
text_font_size="8pt", text_align="center", text_baseline="middle")
# 半徑
p.annular_wedge(0, 0, inner_radius - 10, outer_radius + 10,
-big_angle + angles, -big_angle + angles, color="black")
# 細(xì)菌標(biāo)簽
xr = radii[0] * np.cos(np.array(-big_angle / 2 + angles))
yr = radii[0] * np.sin(np.array(-big_angle / 2 + angles))
label_angle = np.array(-big_angle / 2 + angles)
label_angle[label_angle < -np.pi / 2] += np.pi # easier to read labels on the left side
# 繪制各個(gè)細(xì)菌的名字
p.text(xr, yr, df.bacteria, angle=label_angle,
text_font_size="9pt", text_align="center", text_baseline="middle")
# 繪制圓形关霸,其中數(shù)字分別為 x 軸與 y 軸標(biāo)簽
p.circle([-40, -40], [-370, -390], color=list(gram_color.values()), radius=5)
# 繪制文字
p.text([-30, -30], [-370, -390], text=["Gram-" + gr for gr in gram_color.keys()],
text_font_size="7pt", text_align="left", text_baseline="middle")
# 繪制矩形传黄,中間標(biāo)簽部分。其中 -40队寇,-40膘掰,-40 為三個(gè)矩形的 x 軸坐標(biāo)。18佳遣,0识埋,-18 為三個(gè)矩形的 y 軸坐標(biāo)
p.rect([-40, -40, -40], [18, 0, -18], width=30, height=13,
color=list(drug_color.values()))
# 配置中間標(biāo)簽文字、文字大小零渐、文字對(duì)齊方式
p.text([-15, -15, -15], [18, 0, -18], text=list(drug_color),
text_font_size="9pt", text_align="left", text_baseline="middle")
output_file("burtin.html", title="burtin.py example")
show(p)
元素周期表
元素周期表窒舟,這個(gè)實(shí)現(xiàn)好牛逼啊,距離初三剛開始學(xué)化學(xué)已經(jīng)很遙遠(yuǎn)了诵盼,想當(dāng)年我還是化學(xué)課代表呢惠豺!由于基本用不到化學(xué)了,這里就不實(shí)現(xiàn)了风宁。
大禮包詳見個(gè)人主頁簡(jiǎn)介或者私信獲取