本文共 17445 字,大约阅读时间需要 58 分钟。
python绘制直方图数据
“如何在Python中绘制图?” 过去有一个简单的答案:Matplotlib是唯一的方法。 如今,Python是的语言,并且还有更多选择。 你应该用什么?
Matplotlib , Seaborn , Plotly和 Bokeh —还有几个很有 前途的考虑: Altair (具有表现力的API)和 Pygal (具有出色的SVG输出)。 我还将看一下 pandas提供的非常方便的绘图API。对于每个库,我都提供了源代码片段,以及使用的完整的基于Web的示例, 是我们的平台,仅使用Python即可构建Web应用程序。 让我们来看看。
每个库采用略有不同的方法来绘制数据。 为了进行比较,我将对每个库进行相同的绘制并向您显示源代码。 对于我的示例数据,我选择了自1966年以来的英国大选结果分组条形图:
我从Wikipedia收集了的 :从1966年至2019年,每次选举中保守党,工党和自由党在英国议会中赢得的席位(广义定义),加上“其他”获得的席位”。 您可以 。
是最古老的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之上的抽象层。 它为您提供了一个真正简洁的界面,可以非常轻松地制作各种有用的绘图类型。
但是,它并不会影响功耗! 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 ( )
并生成此图:
是一个包含Python绘图库的绘图生态系统。 它具有三个不同的接口:
情节图旨在嵌入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 ( )
选举结果图:
(发音为“ 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
和剧情:
基于称为的说明性绘图语言(或“可视化语法”)。 这意味着它是一种经过深思熟虑的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' )
以及结果图:
专注于视觉外观。 默认情况下,它会生成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' )
和图表:
是一个非常流行的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 ( )
以及结果图:
要运行此示例,请在签出。
Python提供了许多无需大量代码即可绘制相同数据的方法。 尽管您可以使用这些方法中的任何一种快速开始创建图表,但是它们确实需要一些本地配置。 如果需要, 可为Python开发提供基于Web的优美体验。 密谋快乐!
本文基于 Anvil博客上 ,并在获得许可的情况下重复使用。
翻译自:
python绘制直方图数据
转载地址:http://adbzd.baihongyu.com/