Python drawing--columnar chart

Source: Internet
Author: User
Tags scalar
python drawing--Columnar chart

On the basis of the previous (Python drawing-simple start and line chart), let's draw a bar chart

There are two kinds of columnar graphs (one for histogram and the other for bar chart) One, bar chart

The main methods are:


Atplotlib.pyplot.bar (left, height, width=0.8, Bottom=none, Hold=none, Data=none, **kwargs)

Parameter description:

Left: The x-coordinate of each column

Height: heights of each column

Width: widths between columns

Bottom: The y-coordinate of the column

Color: Column Colors

The following is a code example:

#-*-Coding:utf-8-*-
import numpy as NP  
import Matplotlib.mlab as Mlab  
import Matplotlib.pyplot as Plt  

x=[0,1,2,3,4,5]
y=[222,42,455,664,454,334]  
fig = plt.figure ()
Plt.bar (x,y,0.4,color= "green")
Plt.xlabel ("x-axis")
Plt.ylabel ("Y-axis")
plt.title ("bar chart") Plt.show (
  

)  
plt.savefig (" Barchart.jpg ")

The results are as follows:



Here is another example:

#-*-Coding:utf-8-*-
import numpy as NP
import Matplotlib.pyplot as Plt
import matplotlib as MPL

def Dr Aw_bar (labels,quants):
    width = 0.4
    ind = np.linspace (0.5,9.5,10)
    # make a square figure
    fig = plt.figure (1)
    Ax  = fig.add_subplot (+)
    # Bar Plot
    ax.bar (ind-width/2,quants,width,color= ' green ')
    # Set the Ticks on x-axis
    ax.set_xticks (Ind)
    ax.set_xticklabels (labels)
    # labels
    Ax.set_xlabel (' Country ')
    Ax.set_ylabel (' GDP (billion US dollar) ')
    # title
    ax.set_title (' Top GDP Countries ', bbox={') Facecolor ': ' 0.8 ', ' Pad ': 5} '
    Plt.grid (True)
    plt.show ()
    plt.savefig ("bar.jpg")
    Plt.close ()

labels   = [' USA ', ', ', ' India ', ' Japan ', ' Germany ', ' Russia ', ' Brazil ', ' UK ', ' France ', ' Italy ']

quants   = [15094025.0, 11299967.0, 4457784.0, 4440376.0, 3099080.0, 2383402.0, 2293954.0, 2260803.0, 2217900.0, 1846950.0]

Draw_pie (labels,quants)
The results are as follows:



The following is an official document about the bar chart:

Link: http://matplotlib.org/api/pyplot_api.html

Matplotlib.pyplot. Bar (left, height, width=0.8, Bottom=none, Hold=none, Data=none, **kwargs)

Make a bar plot.

Make a bar plot with rectangles bounded by:left, left + width, bottom, bottom + height (left, right, bottom and top Edges

Parameters:

Left: sequence of scalars

The x coordinates of the left sides of the bars

height : sequence of scalars

The heights of the bars

width : scalar or array-like, optional

The width (s) of the bars default:0.8

Bottom : scalar or array-like, optional

The Y coordinate (s) of the bars Default:none

color : scalar or array-like, optional

The colors of the bar faces

edgecolor : scalar or array-like, optional

The colors of the bar edges

linewidth : scalar or array-like, optional

Width of Bar edge (s). If None, use default linewidth; If 0, don ' t draw edges. Default:none

Tick_label : String or array-like, optional

The tick labels of the bars Default:none

xerr : scalar or array-like, optional

If not None, 'll is used to generate ErrorBar (s) on the bar chart Default:none

yerr : scalar or array-like, optional

If not None, 'll is used to generate ErrorBar (s) on the bar chart Default:none

ecolor : scalar or array-like, optional

Specifies the color of ErrorBar (s) default:none

capsize : scalar, optional

Determines the length in points of the error bar caps Default:none, which'll take the value from Theerrorbar.capsize RC Param.

error_kw : dict, optional

Dictionary of Kwargs to is passed to ErrorBar method. EColor and capsize May is specified here rather than as independent Kwargs.

align : {' Edge ', ' center '}, optional

If ' Edge ', aligns bars by their left edges (for vertical bars) and by their bottom (for edges horizontal). If ' center ', interpret the left argument as the coordinates of the centers of the bars. To align in the align bars on the right edge pass a negative width.

orientation : {' vertical ', ' horizontal '}, optional

The orientation of the bars.

Log : boolean, optional

If true, sets the axis to be log scale. Default:false

Returns:

Bars : Matplotlib.container.BarContainer

Container with the bars + errorbars

Also Barh Plot a horizontal bar Plot.

Notes

In addition to the above described arguments, this function can take a data keyword argument. If such a data argument is given, following arguments are replaced by Data[<arg>]: All Argumen TS with the following names: ' Height ', ' color ', ' ecolor ', ' edgecolor ', ' bottom ', ' Tick_label ', ' width ', ' yerr ', ' xerr ', ' l Inewidth ', ' left '.

Additional Kwargs:hold = [true| False] Overrides default hold state

Examples

Example: A Stacked bar chart.

(Source code, PNG, Hires.png, pdf)

Second, histogram

<span style= "font-family:arial, Helvetica, Sans-serif; Background-color:rgb (255, 255, 255); > The main use of the method is:</span>

Plt.hist ()

Let's take a look at the hist parameters:

Matplotlib.pyplot.hist (  
x, bins=10, Range=none, Normed=false, Weights=none, Cumulative=false,   
Bottom=none,   
histtype=u ' Bar ', Align=u ' mid ', orientation=u ' vertical ', Rwidth=none, Log=false, Color=none, Label=none,   
Stacked=false,   
Hold=none, **kwargs)  

x : (n,) array or sequence of (n,) arrays

This parameter is the data that specifies the distribution of each bin (box), corresponding to the X axis

Bins : integer or array_like, optional

This parameter specifies the number of bin (box), which is a total of several bar graphs

normed : boolean, optional

If True, the ' return tuple would be the ' counts normalized to form a probability density, i.e.,n/(len (x) ' Dbin)

This parameter specifies the density, which is the ratio of each bar graph to the default of 1

color : Color or array_like of colors or None, optional

This specifies the color of the bar chart


The code is as follows:

#-*-Coding:utf-8-*-
import numpy as NP  
import Matplotlib.mlab as Mlab  
import Matplotlib.pyplot as Plt  
  
  
# data  
mu = # mean of distribution  
sigma = # standard deviation of distribution  
x = mu + sigma * Np.rando M.RANDN (10000)  
  
num_bins = # The histogram of the  
data  
N, bins, patches = plt.hist (x, Num_bins, normed=1, F Acecolor= ' Blue ', alpha=0.5)  

# Add a ' best fit ' line  
y = mlab.normpdf (bins, mu, sigma)  
plt.plot (bins, y, ' r -')  
Plt.xlabel (' Smarts ')  
plt.ylabel (' probability ')  
plt.title (R ' Histogram of IQ: $\mu=100$, $\sigma= 15$ ')  
  
# Tweak spacing to prevent clipping of Ylabel  
plt.subplots_adjust (left=0.15)  
plt.show ()  
Plt.savefig ("Hist.jpg")

The results are as follows:


The following is a description of the official document:

Link: http://matplotlib.org/api/pyplot_api.html

Matplotlib.pyplot hist (x, bins=10, Range=none, Normed=false, Weights=none, Cumulative=false, Bottom=none, Histty Pe= ' Bar ', align= ' mid ', orientation= ' vertical ', Rwidth=none, Log=false, Color=none, Label=none, Stacked=false, hold= None, Data=none, **kwargs)

Plot a histogram.

Compute and draw the histogram of X. The return value is a tuple (n, bins, patches) or ([N0, N1, ...], bins, [Patches0, Patches1,...]) If the input contains MU Ltiple data.

Multiple data can be provided via X as a list of datasets of potentially different length ([X0, X1, ...]), or as a 2-d NDA Rray in which each column is a dataset. The Ndarray form is transposed relative to the list form.

Masked arrays are not supported at present.

Parameters:

x  : (n,) array or Sequence of (n) arrays

Input values, this takes either a single array or a sequency of arrays which Red to being of the same length

bins  : integer or array_like, optional

If an integer is Given, bins + 1 bin edges are returned, consistently with numpy.histogram ()  for Version >= 1.3.

unequally spaced bins are supported if bins is a sequence.

Default is ten

range  : Tuple or None, optional

The lower and upper range of the bins. Lower and upper outliers are ignored. If not Provided, range is (X.min (), X.max ()). Range has no effect if 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.