博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python绘制直方图数据_用Python绘制数据的7种最受欢迎的方法
阅读量:2526 次
发布时间:2019-05-11

本文共 17445 字,大约阅读时间需要 58 分钟。

python绘制直方图数据

“如何在Python中绘制图?” 过去有一个简单的答案:Matplotlib是唯一的方法。 如今,Python是的语言,并且还有更多选择。 你应该用什么?

Matplotlib
Seaborn
Plotly
Bokeh —还有几个很有
前途的考虑:
Altair (具有表现力的API)和
Pygal (具有出色的SVG输出)。 我还将看一下
pandas提供的非常方便的绘图API。

对于每个库,我都提供了源代码片段,以及使用的完整的基于Web的示例, 是我们的平台,仅使用Python即可构建Web应用程序。 让我们来看看。

样例

每个库采用略有不同的方法来绘制数据。 为了进行比较,我将对每个库进行相同的绘制并向您显示源代码。 对于我的示例数据,我选择了自1966年以来的英国大选结果分组条形图:

Bar chart of British election data

我从Wikipedia收集了的 :从1966年至2019年,每次选举中保守党,工党和自由党在英国议会中赢得的席位(广义定义),加上“其他”获得的席位”。 您可以 。

Matplotlib

是最古老的Python绘图库,现在仍然是最受欢迎的库。 它创建于2003年,是 (类似于开源科学计算库)的一部分。

Matplotlib使您可以精确控制绘图-例如,您可以定义绘图栏中每个条形的单独x位置。 这是绘制此图的代码(您可以在运行):

         
import matplotlib.
pyplot
as plt
   
import numpy
as np
   
from votes
import wide
as df
   
# Initialise a figure. subplots() with no args gives one plot.
    fig
, ax
= plt.
subplots
(
)
   
# A little data preparation
    years
= df
[
'year'
]
    x
= np.
arange
(
len
( years
)
)
   
# Plot each bar plot. Note: manually calculating the 'dodges' of the bars
    ax.
bar
( x -
3 *width/
2
, df
[
'conservative'
]
, width
, label
=
'Conservative'
, color
=
'#0343df'
)
    ax.
bar
( x - width/
2
, df
[
'labour'
]
, width
, label
=
'Labour'
, color
=
'#e50000'
)
    ax.
bar
( x + width/
2
, df
[
'liberal'
]
, width
, label
=
'Liberal'
, color
=
'#ffff14'
)
    ax.
bar
( x +
3 *width/
2
, df
[
'others'
]
, width
, label
=
'Others'
, color
=
'#929591'
)
   
# Customise some display properties
    ax.
set_ylabel
(
'Seats'
)
    ax.
set_title
(
'UK election results'
)
    ax.
set_xticks
( x
)    
# This ensures we have one tick per year, otherwise we get fewer
    ax.
set_xticklabels
( years.
astype
(
str
) .
values
, rotation
=
'vertical'
)
    ax.
legend
(
)
   
# Ask Matplotlib to show the plot
    plt.
show
(
)

这是Matplotlib中绘制的选举结果:

Matplotlib plot of British election data

海生

是Matplotlib之上的抽象层。 它为您提供了一个真正简洁的界面,可以非常轻松地制作各种有用的绘图类型。

但是,它并不会影响功耗! Seaborn提供了来访问底层的Matplotlib对象,因此您仍然拥有完全的控制权。

Seaborn的代码比原始Matplotlib(可运行)简单:

         
import seaborn
as sns
   
from votes
import
long
as df
   
# Some boilerplate to initialise things
    sns.
set
(
)
    plt.
figure
(
)
   
# This is where the actual plot gets made
    ax
= sns.
barplot
( data
= df
, x
=
"year"
, y
=
"seats"
, hue
=
"party"
, palette
=
[
'blue'
,
'red'
,
'yellow'
,
'grey'
]
, saturation
=
0.6
)
   
# Customise some display properties
    ax.
set_title
(
'UK election results'
)
    ax.
grid
( color
=
'#cccccc'
)
    ax.
set_ylabel
(
'Seats'
)
    ax.
set_xlabel
(
None
)
    ax.
set_xticklabels
( df
[
"year"
] .
unique
(
) .
astype
(
str
)
, rotation
=
'vertical'
)
   
# Ask Matplotlib to show it
    plt.
show
(
)

并生成此图:

Seaborn plot of British election data

密谋

是一个包含Python绘图库的绘图生态系统。 它具有三个不同的接口:

  • 面向对象的界面
  • 命令式界面,使您可以使用类似JSON的数据结构来指定绘图
  • 与Seaborn类似的高级界面称为Plotly Express

情节图旨在嵌入Web应用程序中。 本质上,Plotly实际上是一个JavaScript库! 它使用和绘制图。

您可以通过将JSON传递给JavaScript库来以其他语言构建Plotly库。 官方的Python和R库就是这样做的。 在Anvil,我们移植了Python Plotly API以 。

这是Plotly中的源代码(可以在运行):

         
import plotly.
graph_objects
as go
   
from votes
import wide
as df
   
#  Get a convenient list of x-values
    years
= df
[
'year'
]
    x
=
list
(
range
(
len
( years
)
)
)
   
# Specify the plots
    bar_plots
=
[
        go.
Bar
( x
= x
, y
= df
[
'conservative'
]
, name
=
'Conservative'
, marker
= go.
bar .
Marker
( color
=
'#0343df'
)
)
,
        go.
Bar
( x
= x
, y
= df
[
'labour'
]
, name
=
'Labour'
, marker
= go.
bar .
Marker
( color
=
'#e50000'
)
)
,
        go.
Bar
( x
= x
, y
= df
[
'liberal'
]
, name
=
'Liberal'
, marker
= go.
bar .
Marker
( color
=
'#ffff14'
)
)
,
        go.
Bar
( x
= x
, y
= df
[
'others'
]
, name
=
'Others'
, marker
= go.
bar .
Marker
( color
=
'#929591'
)
)
,
   
]
   
# Customise some display properties
    layout
= go.
Layout
(
        title
= go.
layout .
Title
( text
=
"Election results"
, x
=
0.5
)
,
        yaxis_title
=
"Seats"
,
        xaxis_tickmode
=
"array"
,
        xaxis_tickvals
=
list
(
range
(
27
)
)
,
        xaxis_ticktext
=
tuple
( df
[
'year'
] .
values
)
,
   
)
   
# Make the multi-bar plot
    fig
= go.
Figure
( data
= bar_plots
, layout
= layout
)
   
# Tell Plotly to render it
    fig.
show
(
)

选举结果图:

Plotly plot of British election data

散景

(发音为“ BOE-kay”)专门从事构建交互式地块,因此,此标准示例并未充分发挥其作用。 与Plotly一样,Bokeh的地块旨在嵌入到Web应用程序中。 它将其图输出为HTML文件。

这是Bokeh中的代码(您可以在运行)

         
from bokeh.
io
import show
, output_file
   
from bokeh.
models
import ColumnDataSource
, FactorRange
, HoverTool
   
from bokeh.
plotting
import figure
   
from bokeh.
transform
import factor_cmap
   
from votes
import
long
as df
   
# Specify a file to write the plot to
    output_file
(
"elections.html"
)
   
# Tuples of groups (year, party)
    x
=
[
(
str
( r
[
1
]
[
'year'
]
)
, r
[
1
]
[
'party'
]
)
for r
in df.
iterrows
(
)
]
    y
= df
[
'seats'
]
   
# Bokeh wraps your data in its own objects to support interactivity
    source
= ColumnDataSource
( data
=
dict
( x
= x
, y
= y
)
)
   
# Create a colourmap
    cmap
=
{
       
'Conservative' :
'#0343df'
,
       
'Labour' :
'#e50000'
,
       
'Liberal' :
'#ffff14'
,
       
'Others' :
'#929591'
,
   
}
    fill_color
= factor_cmap
(
'x'
, palette
=
list
( cmap.
values
(
)
)
, factors
=
list
( cmap.
keys
(
)
)
, start
=
1
, end
=
2
)
   
# Make the plot
    p
= figure
( x_range
= FactorRange
( *x
)
, width
=
1200
, title
=
"Election results"
)
    p.
vbar
( x
=
'x'
, top
=
'y'
, width
=
0.9
, source
= source
, fill_color
= fill_color
, line_color
= fill_color
)
   
# Customise some display properties
    p.
y_range .
start
=
0
    p.
x_range .
range_padding
=
0.1
    p.
yaxis .
axis_label
=
'Seats'
    p.
xaxis .
major_label_orientation
=
1
    p.
xgrid .
grid_line_color
=
None

和剧情:

Bokeh plot of British election data

牵牛星

基于称为的说明性绘图语言(或“可视化语法”)。 这意味着它是一种经过深思熟虑的API,可以很好地缩放复杂图,从而避免您陷入嵌套循环地狱中。

与Bokeh一样,Altair将其图输出为HTML文件。 这是代码(您可以在运行):

         
import altair
as alt
   
from votes
import
long
as df
   
# Set up the colourmap
    cmap
=
{
       
'Conservative' :
'#0343df'
,
       
'Labour' :
'#e50000'
,
       
'Liberal' :
'#ffff14'
,
       
'Others' :
'#929591'
,
   
}
   
# Cast years to strings
    df
[
'year'
]
= df
[
'year'
] .
astype
(
str
)
   
# Here's where we make the plot
    chart
= alt.
Chart
( df
) .
mark_bar
(
) .
encode
(
        x
= alt.
X
(
'party'
, title
=
None
)
,
        y
=
'seats'
,
        column
= alt.
Column
(
'year'
, sort
=
list
( df
[
'year'
]
)
, title
=
None
)
,
        color
= alt.
Color
(
'party'
, scale
= alt.
Scale
( domain
=
list
( cmap.
keys
(
)
)
,
range
=
list
( cmap.
values
(
)
)
)
)
   
)
   
# Save it as an HTML file.
    chart.
save
(
'altair-elections.html'
)

以及结果图:

Altair plot of British election data

皮加尔

专注于视觉外观。 默认情况下,它会生成SVG图,因此您可以永久缩放它们或将其打印出来而不会变得像素化。 Pygal图还具有一些内置的良好交互功能,如果您希望将图嵌入Web应用程序,则Pygal会成为另一个被低估的候选对象。

源代码如下所示(您可以在运行):

         
import pygal
   
from pygal.
style
import Style
   
from votes
import wide
as df
   
# Define the style
    custom_style
= Style
(
        colors
=
(
'#0343df'
,
'#e50000'
,
'#ffff14'
,
'#929591'
)
        font_family
=
'Roboto,Helvetica,Arial,sans-serif'
,
        background
=
'transparent'
,
        label_font_size
=
14
,
   
)
   
# Set up the bar plot, ready for data
    c
= pygal.
Bar
(
        title
=
"UK Election Results"
,
        style
= custom_style
,
        y_title
=
'Seats'
,
        width
=
1200
,
        x_label_rotation
=
270
,
   
)
   
# Add four data sets to the bar plot
    c.
add
(
'Conservative'
, df
[
'conservative'
]
)
    c.
add
(
'Labour'
, df
[
'labour'
]
)
    c.
add
(
'Liberal'
, df
[
'liberal'
]
)
    c.
add
(
'Others'
, df
[
'others'
]
)
   
# Define the X-labels
    c.
x_labels
= df
[
'year'
]
   
# Write this to an SVG file
    c.
render_to_file
(
'pygal.svg'
)

和图表:

Pygal plot of British election data

大熊猫

是一个非常流行的Python数据科学库。 它允许您按比例进行各种数据处理,但是它还具有方便的绘图API。 因为pandas示例直接在数据帧上运行,所以它是本文中最简洁的代码段,甚至比Seaborn代码还短!

熊猫API是Matplotlib的包装,因此您还可以使用底层Matplotlib API来获得对图的细粒度控制。

这是大熊猫的选举结果图。 代码简明扼要!

         
from matplotlib.
colors
import ListedColormap
   
from votes
import wide
as df
    cmap
= ListedColormap
(
[
'#0343df'
,
'#e50000'
,
'#ffff14'
,
'#929591'
]
)
    ax
= df.
plot .
bar
( x
=
'year'
, colormap
= cmap
)
    ax.
set_xlabel
(
None
)
    ax.
set_ylabel
(
'Seats'
)
    ax.
set_title
(
'UK election results'
)
    plt.
show
(
)

以及结果图:

Pandas plot of British election data

要运行此示例,请在签出。

画出自己的路

Python提供了许多无需大量代码即可绘制相同数据的方法。 尽管您可以使用这些方法中的任何一种快速开始创建图表,但是它们确实需要一些本地配置。 如果需要, 可为Python开发提供基于Web的优美体验。 密谋快乐!


本文基于 Anvil博客上 ,并在获得许可的情况下重复使用。

翻译自:

python绘制直方图数据

转载地址:http://adbzd.baihongyu.com/

你可能感兴趣的文章
012 debug调试工具的指令
查看>>
慕课网消息的接收与响应3
查看>>
第三十二讲:UML类图(下)
查看>>
linux下更改时区
查看>>
复杂链表的复制
查看>>
code vs 3376 符号三角形
查看>>
[CF193B] Xor(暴力,剪枝,异或)
查看>>
[CF825D] Suitable Replacement (贪心乱搞)
查看>>
大数据笔记(二十五)——Scala函数式编程
查看>>
win7 IIS7 运行vs2003 web 项目 无法识别的配置节“system.webServer” 解决
查看>>
jQuery源码分析_工具方法(学习笔记)
查看>>
有穷自动机的转换
查看>>
ncbi-blast 本地安装
查看>>
在android上使用 stand-alone toolchains移植 transmission
查看>>
小议IT公司的组织架构
查看>>
在Eclipse中编写jQuery代码时产生的错误(连载)
查看>>
java 中 this的使用
查看>>
HTTP详解
查看>>
编程和技术不是一回事!
查看>>
java小练习--获取abc字符串在整个字符串中出现的次数
查看>>