# python画图－－柱状图

## 一、bar chart

atplotlib.pyplot.bar(leftheightwidth=0.8bottom=Nonehold=Nonedata=None**kwargs)

left: 每一个柱形左侧的X坐标

height:每一个柱形的高度

width: 柱形之间的宽度

bottom: 柱形的Y坐标

color: 柱形的颜色

# -*- 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")


# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

def draw_bar(labels,quants):
width = 0.4
ind = np.linspace(0.5,9.5,10)
# make a square figure
fig = plt.figure(1)
# 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 10 GDP Countries', bbox={'facecolor':'0.8', 'pad':5})
plt.grid(True)
plt.show()
plt.savefig("bar.jpg")
plt.close()

labels   = ['USA', 'China', '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)

matplotlib.pyplot.bar(leftheightwidth=0.8bottom=Nonehold=Nonedata=None**kwargs)

Make a bar plot.

Make a bar plot with rectangles bounded by:

leftleft + widthbottombottom + 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, will be used to generate errorbar(s) on the bar chart default: None yerr : scalar or array-like, optional if not None, will be 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 will take the value from theerrorbar.capsize rcParam. error_kw : dict, optional dictionary of kwargs to be passed to errorbar method. ecolor and capsize may be 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 edges (for horizontal bars). If ‘center’, interpret the left argument as the coordinates of the centers of the bars. To align on 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 bars : matplotlib.container.BarContainer Container with all of the bars + errorbars

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, the following arguments are replaced by data[<arg>]:

• All arguments with the following names: ‘height’, ‘color’, ‘ecolor’, ‘edgecolor’, ‘bottom’, ‘tick_label’, ‘width’, ‘yerr’, ‘xerr’, ‘linewidth’, ‘left’.

Additional kwargs: hold = [True|False] overrides default hold state

Examples

Example: A stacked bar chart.

## 二、histogram

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">主要用的的方法为：</span>

plt.hist()

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

bins : integer or array_like, optional

normed : boolean, optional

If True, the first element of the return tuple will be the counts normalized to form a probability density, i.e.,n/(len(x)dbin)

color : color or array_like of colors or None, optional

# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

# 数据
mu = 100 # mean of distribution
sigma = 15 # standard deviation of distribution
x = mu + sigma * np.random.randn(10000)

num_bins = 50
# the histogram of the data
n, bins, patches = plt.hist(x, num_bins, normed=1, facecolor='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.show()
plt.savefig("hist.jpg")

matplotlib.pyplot.hist(xbins=10range=Nonenormed=Falseweights=Nonecumulative=Falsebottom=Nonehisttype='bar'align='mid',orientation='vertical'rwidth=Nonelog=Falsecolor=Nonelabel=Nonestacked=Falsehold=Nonedata=None**kwargs)

Plot a histogram.

Compute and draw the histogram of x. The return value is a tuple (nbinspatches) or ([n0n1, ...], bins, [patches0patches1,...]) if the input contains multiple data.

Multiple data can be provided via x as a list of datasets of potentially different length ([x0x1, ...]), or as a 2-D ndarray in which each column is a dataset. Note that 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 are not required to be 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 numpy version >= 1.3. Unequally spaced bins are supported if bins is a sequence. default is 10 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 bins is a sequence. If bins is a sequence or range is specified, autoscaling is based on the specified bin range instead of the range of x. Default is None normed : boolean, optional If True, the first element of the return tuple will be the counts normalized to form a probability density, i.e.,n/(len(x)dbin), i.e., the integral of the histogram will sum to 1. If stacked is also True, the sum of the histograms is normalized to 1. Default is False weights : (n, ) array_like or None, optional An array of weights, of the same shape as x. Each value in x only contributes its associated weight towards the bin count (instead of 1). If normed is True, the weights are normalized, so that the integral of the density over the range remains 1. Default is None cumulative : boolean, optional If True, then a histogram is computed where each bin gives the counts in that bin plus all bins for smaller values. The last bin gives the total number of datapoints. If normed is also True then the histogram is normalized such that the last bin equals 1. If cumulative evaluates to less than 0 (e.g., -1), the direction of accumulation is reversed. In this case, if normed is also True, then the histogram is normalized such that the first bin equals 1. Default is False bottom : array_like, scalar, or None Location of the bottom baseline of each bin. If a scalar, the base line for each bin is shifted by the same amount. If an array, each bin is shifted independently and the length of bottom must match the number of bins. If None, defaults to 0. Default is None histtype : {‘bar’, ‘barstacked’, ‘step’, ‘stepfilled’}, optional The type of histogram to draw. ‘bar’ is a traditional bar-type histogram. If multiple data are given the bars are aranged side by side.‘barstacked’ is a bar-type histogram where multiple data are stacked on top of each other.‘step’ generates a lineplot that is by default unfilled.‘stepfilled’ generates a lineplot that is by default filled. Default is ‘bar’ align : {‘left’, ‘mid’, ‘right’}, optional Controls how the histogram is plotted. ‘left’: bars are centered on the left bin edges.‘mid’: bars are centered between the bin edges.‘right’: bars are centered on the right bin edges. Default is ‘mid’ orientation : {‘horizontal’, ‘vertical’}, optional If ‘horizontal’, barh will be used for bar-type histograms and the bottom kwarg will be the left edges. rwidth : scalar or None, optional The relative width of the bars as a fraction of the bin width. If None, automatically compute the width. Ignored if histtype is ‘step’ or ‘stepfilled’. Default is None log : boolean, optional If True, the histogram axis will be set to a log scale. If log is True and x is a 1D array, empty bins will be filtered out and only the non-empty (n, bins, patches) will be returned. Default is False color : color or array_like of colors or None, optional Color spec or sequence of color specs, one per dataset. Default (None) uses the standard line color sequence. Default is None label : string or None, optional String, or sequence of strings to match multiple datasets. Bar charts yield multiple patches per dataset, but only the first gets the label, so that the legend command will work as expected. default is None stacked : boolean, optional If True, multiple data are stacked on top of each other If False multiple data are aranged side by side if histtype is ‘bar’ or on top of each other if histtype is ‘step’ Default is False n : array or list of arrays The values of the histogram bins. See normed and weights for a description of the possible semantics. If input x is an array, then this is an array of length nbins. If input is a sequence arrays [data1, data2,..], then this is a list of arrays with the values of the histograms for each of the arrays in the same order. bins : array The edges of the bins. Length nbins + 1 (nbins left edges and right edge of last bin). Always a single array even when multiple data sets are passed in. patches : list or list of lists Silent list of individual patches used to create the histogram or list of such list if multiple input datasets.

hist2d
2D histograms

Notes

In addition to the above described arguments, this function can take a data keyword argument. If such a data argument is given, the following arguments are replaced by data[<arg>]:

• All arguments with the following names: ‘weights’, ‘x’.

Additional kwargs: hold = [True|False] overrides default hold state

Examples