Movatterモバイル変換


[0]ホーム

URL:


Navigation

Table Of Contents

Search

Enter search terms or a module, class or function name.

Visualization

We use the standard convention for referencing the matplotlib API:

In [1]:importmatplotlib.pyplotasplt

The plots in this document are made using matplotlib’sggplot style (new in version 1.4):

importmatplotlibmatplotlib.style.use('ggplot')

We provide the basics in pandas to easily create decent looking plots.See theecosystem section for visualizationlibraries that go beyond the basics documented here.

Note

All calls tonp.random are seeded with 123456.

Basic Plotting:plot

See thecookbook for some advanced strategies

Theplot method on Series and DataFrame is just a simple wrapper aroundplt.plot():

In [2]:ts=pd.Series(np.random.randn(1000),index=pd.date_range('1/1/2000',periods=1000))In [3]:ts=ts.cumsum()In [4]:ts.plot()Out[4]:<matplotlib.axes._subplots.AxesSubplotat0x7fd2371f2c10>
_images/series_plot_basic.png

If the index consists of dates, it callsgcf().autofmt_xdate()to try to format the x-axis nicely as per above.

On DataFrame,plot() is a convenience to plot all of the columns with labels:

In [5]:df=pd.DataFrame(np.random.randn(1000,4),index=ts.index,columns=list('ABCD'))In [6]:df=df.cumsum()In [7]:plt.figure();df.plot();
_images/frame_plot_basic.png

You can plot one column versus another using thex andy keywords inplot():

In [8]:df3=pd.DataFrame(np.random.randn(1000,2),columns=['B','C']).cumsum()In [9]:df3['A']=pd.Series(list(range(len(df))))In [10]:df3.plot(x='A',y='B')Out[10]:<matplotlib.axes._subplots.AxesSubplotat0x7fd234b15210>
_images/df_plot_xy.png

Note

For more formatting and styling options, seebelow.

Other Plots

Plotting methods allow for a handful of plot styles other than thedefault Line plot. These methods can be provided as thekindkeyword argument toplot().These include:

For example, a bar plot can be created the following way:

In [11]:plt.figure();In [12]:df.ix[5].plot(kind='bar');plt.axhline(0,color='k')Out[12]:<matplotlib.lines.Line2Dat0x7fd234a55b50>
_images/bar_plot_ex.png

New in version 0.17.0.

You can also create these other plots using the methodsDataFrame.plot.<kind> instead of providing thekind keyword argument. This makes it easier to discover plot methods and the specific arguments they use:

In [13]:df=pd.DataFrame()In [14]:df.plot.<TAB>df.plot.area     df.plot.barh     df.plot.density  df.plot.hist     df.plot.line     df.plot.scatterdf.plot.bar      df.plot.box      df.plot.hexbin   df.plot.kde      df.plot.pie

In addition to thesekind s, there are theDataFrame.hist(),andDataFrame.boxplot() methods, which use a separate interface.

Finally, there are severalplotting functions inpandas.tools.plottingthat take aSeries orDataFrame as an argument. Theseinclude

Plots may also be adorned witherrorbarsortables.

Bar plots

For labeled, non-time series data, you may wish to produce a bar plot:

In [15]:plt.figure();In [16]:df.ix[5].plot.bar();plt.axhline(0,color='k')Out[16]:<matplotlib.lines.Line2Dat0x7fd237132650>
_images/bar_plot_ex.png

Calling a DataFrame’splot.bar() method produces a multiplebar plot:

In [17]:df2=pd.DataFrame(np.random.rand(10,4),columns=['a','b','c','d'])In [18]:df2.plot.bar();
_images/bar_plot_multi_ex.png

To produce a stacked bar plot, passstacked=True:

In [19]:df2.plot.bar(stacked=True);
_images/bar_plot_stacked_ex.png

To get horizontal bar plots, use thebarh method:

In [20]:df2.plot.barh(stacked=True);
_images/barh_plot_stacked_ex.png

Histograms

New in version 0.15.0.

Histogram can be drawn by using theDataFrame.plot.hist() andSeries.plot.hist() methods.

In [21]:df4=pd.DataFrame({'a':np.random.randn(1000)+1,'b':np.random.randn(1000),   ....:'c':np.random.randn(1000)-1},columns=['a','b','c'])   ....:In [22]:plt.figure();In [23]:df4.plot.hist(alpha=0.5)Out[23]:<matplotlib.axes._subplots.AxesSubplotat0x7fd23f128710>
_images/hist_new.png

Histogram can be stacked bystacked=True. Bin size can be changed bybins keyword.

In [24]:plt.figure();In [25]:df4.plot.hist(stacked=True,bins=20)Out[25]:<matplotlib.axes._subplots.AxesSubplotat0x7fd2347c1290>
_images/hist_new_stacked.png

You can pass other keywords supported by matplotlibhist. For example, horizontal and cumulative histgram can be drawn byorientation='horizontal' andcumulative='True'.

In [26]:plt.figure();In [27]:df4['a'].plot.hist(orientation='horizontal',cumulative=True)Out[27]:<matplotlib.axes._subplots.AxesSubplotat0x7fd24df0bb90>
_images/hist_new_kwargs.png

See thehist method and thematplotlib hist documentation for more.

The existing interfaceDataFrame.hist to plot histogram still can be used.

In [28]:plt.figure();In [29]:df['A'].diff().hist()Out[29]:<matplotlib.axes._subplots.AxesSubplotat0x7fd24bb4b690>
_images/hist_plot_ex.png

DataFrame.hist() plots the histograms of the columns on multiplesubplots:

In [30]:plt.figure()Out[30]:<matplotlib.figure.Figureat0x7fd2405dfa50>In [31]:df.diff().hist(color='k',alpha=0.5,bins=50)Out[31]:array([[<matplotlib.axes._subplots.AxesSubplot object at 0x7fd24064bb10>,        <matplotlib.axes._subplots.AxesSubplot object at 0x7fd234accb10>],       [<matplotlib.axes._subplots.AxesSubplot object at 0x7fd23485e510>,        <matplotlib.axes._subplots.AxesSubplot object at 0x7fd2370f8590>]], dtype=object)
_images/frame_hist_ex.png

New in version 0.10.0.

Theby keyword can be specified to plot grouped histograms:

In [32]:data=pd.Series(np.random.randn(1000))In [33]:data.hist(by=np.random.randint(0,4,1000),figsize=(6,4))Out[33]:array([[<matplotlib.axes._subplots.AxesSubplot object at 0x7fd234ac0a10>,        <matplotlib.axes._subplots.AxesSubplot object at 0x7fd23f221890>],       [<matplotlib.axes._subplots.AxesSubplot object at 0x7fd23f9cded0>,        <matplotlib.axes._subplots.AxesSubplot object at 0x7fd23d964410>]], dtype=object)
_images/grouped_hist.png

Box Plots

New in version 0.15.0.

Boxplot can be drawn callingSeries.plot.box() andDataFrame.plot.box(),orDataFrame.boxplot() to visualize the distribution of values within each column.

For instance, here is a boxplot representing five trials of 10 observations ofa uniform random variable on [0,1).

In [34]:df=pd.DataFrame(np.random.rand(10,5),columns=['A','B','C','D','E'])In [35]:df.plot.box()Out[35]:<matplotlib.axes._subplots.AxesSubplotat0x7fd234ea5790>
_images/box_plot_new.png

Boxplot can be colorized by passingcolor keyword. You can pass adictwhose keys areboxes,whiskers,medians andcaps.If some keys are missing in thedict, default colors are usedfor the corresponding artists. Also, boxplot hassym keyword to specify fliers style.

When you pass other type of arguments viacolor keyword, it will be directlypassed to matplotlib for all theboxes,whiskers,medians andcapscolorization.

The colors are applied to every boxes to be drawn. If you wantmore complicated colorization, you can get each drawn artists by passingreturn_type.

In [36]:color=dict(boxes='DarkGreen',whiskers='DarkOrange',   ....:medians='DarkBlue',caps='Gray')   ....:In [37]:df.plot.box(color=color,sym='r+')Out[37]:<matplotlib.axes._subplots.AxesSubplotat0x7fd234e8cc10>
_images/box_new_colorize.png

Also, you can pass other keywords supported by matplotlibboxplot.For example, horizontal and custom-positioned boxplot can be drawn byvert=False andpositions keywords.

In [38]:df.plot.box(vert=False,positions=[1,4,5,6,8])Out[38]:<matplotlib.axes._subplots.AxesSubplotat0x7fd2357a0610>
_images/box_new_kwargs.png

See theboxplot method and thematplotlib boxplot documentation for more.

The existing interfaceDataFrame.boxplot to plot boxplot still can be used.

In [39]:df=pd.DataFrame(np.random.rand(10,5))In [40]:plt.figure();In [41]:bp=df.boxplot()
_images/box_plot_ex.png

You can create a stratified boxplot using theby keyword argument to creategroupings. For instance,

In [42]:df=pd.DataFrame(np.random.rand(10,2),columns=['Col1','Col2'])In [43]:df['X']=pd.Series(['A','A','A','A','A','B','B','B','B','B'])In [44]:plt.figure();In [45]:bp=df.boxplot(by='X')
_images/box_plot_ex2.png

You can also pass a subset of columns to plot, as well as group by multiplecolumns:

In [46]:df=pd.DataFrame(np.random.rand(10,3),columns=['Col1','Col2','Col3'])In [47]:df['X']=pd.Series(['A','A','A','A','A','B','B','B','B','B'])In [48]:df['Y']=pd.Series(['A','B','A','B','A','B','A','B','A','B'])In [49]:plt.figure();In [50]:bp=df.boxplot(column=['Col1','Col2'],by=['X','Y'])
_images/box_plot_ex3.png

Warning

The default changed from'dict' to'axes' in version 0.19.0.

Inboxplot, the return type can be controlled by thereturn_type, keyword. The valid choices are{"axes","dict","both",None}.Faceting, created byDataFrame.boxplot with thebykeyword, will affect the output type as well:

return_type=FacetedOutput type
NoneNoaxes
NoneYes2-D ndarray of axes
'axes'Noaxes
'axes'YesSeries of axes
'dict'Nodict of artists
'dict'YesSeries of dicts of artists
'both'Nonamedtuple
'both'YesSeries of namedtuples

Groupby.boxplot always returns a Series ofreturn_type.

In [51]:np.random.seed(1234)In [52]:df_box=pd.DataFrame(np.random.randn(50,2))In [53]:df_box['g']=np.random.choice(['A','B'],size=50)In [54]:df_box.loc[df_box['g']=='B',1]+=3In [55]:bp=df_box.boxplot(by='g')
_images/boxplot_groupby.png

Compare to:

In [56]:bp=df_box.groupby('g').boxplot()
_images/groupby_boxplot_vis.png

Area Plot

New in version 0.14.

You can create area plots withSeries.plot.area() andDataFrame.plot.area().Area plots are stacked by default. To produce stacked area plot, each column must be either all positive or all negative values.

When input data containsNaN, it will be automatically filled by 0. If you want to drop or fill by different values, usedataframe.dropna() ordataframe.fillna() before callingplot.

In [57]:df=pd.DataFrame(np.random.rand(10,4),columns=['a','b','c','d'])In [58]:df.plot.area();
_images/area_plot_stacked.png

To produce an unstacked plot, passstacked=False. Alpha value is set to 0.5 unless otherwise specified:

In [59]:df.plot.area(stacked=False);
_images/area_plot_unstacked.png

Scatter Plot

New in version 0.13.

Scatter plot can be drawn by using theDataFrame.plot.scatter() method.Scatter plot requires numeric columns for x and y axis.These can be specified byx andy keywords each.

In [60]:df=pd.DataFrame(np.random.rand(50,4),columns=['a','b','c','d'])In [61]:df.plot.scatter(x='a',y='b');
_images/scatter_plot.png

To plot multiple column groups in a single axes, repeatplot method specifying targetax.It is recommended to specifycolor andlabel keywords to distinguish each groups.

In [62]:ax=df.plot.scatter(x='a',y='b',color='DarkBlue',label='Group 1');In [63]:df.plot.scatter(x='c',y='d',color='DarkGreen',label='Group 2',ax=ax);
_images/scatter_plot_repeated.png

The keywordc may be given as the name of a column to provide colors foreach point:

In [64]:df.plot.scatter(x='a',y='b',c='c',s=50);
_images/scatter_plot_colored.png

You can pass other keywords supported by matplotlibscatter.Below example shows a bubble chart using a dataframe column values as bubble size.

In [65]:df.plot.scatter(x='a',y='b',s=df['c']*200);
_images/scatter_plot_bubble.png

See thescatter method and thematplotlib scatter documentation for more.

Hexagonal Bin Plot

New in version 0.14.

You can create hexagonal bin plots withDataFrame.plot.hexbin().Hexbin plots can be a useful alternative to scatter plots if your data aretoo dense to plot each point individually.

In [66]:df=pd.DataFrame(np.random.randn(1000,2),columns=['a','b'])In [67]:df['b']=df['b']+np.arange(1000)In [68]:df.plot.hexbin(x='a',y='b',gridsize=25)Out[68]:<matplotlib.axes._subplots.AxesSubplotat0x7fd236899390>
_images/hexbin_plot.png

A useful keyword argument isgridsize; it controls the number of hexagonsin the x-direction, and defaults to 100. A largergridsize means more, smallerbins.

By default, a histogram of the counts around each(x,y) point is computed.You can specify alternative aggregations by passing values to theC andreduce_C_function arguments.C specifies the value at each(x,y) pointandreduce_C_function is a function of one argument that reduces all thevalues in a bin to a single number (e.g.mean,max,sum,std). In thisexample the positions are given by columnsa andb, while the value isgiven by columnz. The bins are aggregated with numpy’smax function.

In [69]:df=pd.DataFrame(np.random.randn(1000,2),columns=['a','b'])In [70]:df['b']=df['b']=df['b']+np.arange(1000)In [71]:df['z']=np.random.uniform(0,3,1000)In [72]:df.plot.hexbin(x='a',y='b',C='z',reduce_C_function=np.max,   ....:gridsize=25)   ....:Out[72]:<matplotlib.axes._subplots.AxesSubplotat0x7fd236861d90>
_images/hexbin_plot_agg.png

See thehexbin method and thematplotlib hexbin documentation for more.

Pie plot

New in version 0.14.

You can create a pie plot withDataFrame.plot.pie() orSeries.plot.pie().If your data includes anyNaN, they will be automatically filled with 0.AValueError will be raised if there are any negative values in your data.

In [73]:series=pd.Series(3*np.random.rand(4),index=['a','b','c','d'],name='series')In [74]:series.plot.pie(figsize=(6,6))Out[74]:<matplotlib.axes._subplots.AxesSubplotat0x7fd23e470510>
_images/series_pie_plot.png

For pie plots it’s best to use square figures, one’s with an equal aspect ratio. You can create thefigure with equal width and height, or force the aspect ratio to be equal after plotting bycallingax.set_aspect('equal') on the returnedaxes object.

Note that pie plot withDataFrame requires that you either specify a target column by theyargument orsubplots=True. Wheny is specified, pie plot of selected columnwill be drawn. Ifsubplots=True is specified, pie plots for each column are drawn as subplots.A legend will be drawn in each pie plots by default; specifylegend=False to hide it.

In [75]:df=pd.DataFrame(3*np.random.rand(4,2),index=['a','b','c','d'],columns=['x','y'])In [76]:df.plot.pie(subplots=True,figsize=(8,4))Out[76]:array([<matplotlib.axes._subplots.AxesSubplot object at 0x7fd2367c0f50>,       <matplotlib.axes._subplots.AxesSubplot object at 0x7fd2401bc910>], dtype=object)
_images/df_pie_plot.png

You can use thelabels andcolors keywords to specify the labels and colors of each wedge.

Warning

Most pandas plots use the thelabel andcolor arguments (note the lack of “s” on those).To be consistent withmatplotlib.pyplot.pie() you must uselabels andcolors.

If you want to hide wedge labels, specifylabels=None.Iffontsize is specified, the value will be applied to wedge labels.Also, other keywords supported bymatplotlib.pyplot.pie() can be used.

In [77]:series.plot.pie(labels=['AA','BB','CC','DD'],colors=['r','g','b','c'],   ....:autopct='%.2f',fontsize=20,figsize=(6,6))   ....:Out[77]:<matplotlib.axes._subplots.AxesSubplotat0x7fd234e7c710>
_images/series_pie_plot_options.png

If you pass values whose sum total is less than 1.0, matplotlib draws a semicircle.

In [78]:series=pd.Series([0.1]*4,index=['a','b','c','d'],name='series2')In [79]:series.plot.pie(figsize=(6,6))Out[79]:<matplotlib.axes._subplots.AxesSubplotat0x7fd234e6a110>
_images/series_pie_plot_semi.png

See thematplotlib pie documentation for more.

Plotting with Missing Data

Pandas tries to be pragmatic about plotting DataFrames or Seriesthat contain missing data. Missing values are dropped, left out, or filleddepending on the plot type.

Plot TypeNaN Handling
LineLeave gaps at NaNs
Line (stacked)Fill 0’s
BarFill 0’s
ScatterDrop NaNs
HistogramDrop NaNs (column-wise)
BoxDrop NaNs (column-wise)
AreaFill 0’s
KDEDrop NaNs (column-wise)
HexbinDrop NaNs
PieFill 0’s

If any of these defaults are not what you want, or if you want to beexplicit about how missing values are handled, consider usingfillna() ordropna()before plotting.

Plotting Tools

These functions can be imported frompandas.tools.plottingand take aSeries orDataFrame as an argument.

Scatter Matrix Plot

New in version 0.7.3.

You can create a scatter plot matrix using thescatter_matrix method inpandas.tools.plotting:

In [80]:frompandas.tools.plottingimportscatter_matrixIn [81]:df=pd.DataFrame(np.random.randn(1000,4),columns=['a','b','c','d'])In [82]:scatter_matrix(df,alpha=0.2,figsize=(6,6),diagonal='kde')Out[82]:array([[<matplotlib.axes._subplots.AxesSubplot object at 0x7fd23e828b50>,        <matplotlib.axes._subplots.AxesSubplot object at 0x7fd23c343190>,        <matplotlib.axes._subplots.AxesSubplot object at 0x7fd235c6a7d0>,        <matplotlib.axes._subplots.AxesSubplot object at 0x7fd23f55d150>],       [<matplotlib.axes._subplots.AxesSubplot object at 0x7fd23df195d0>,        <matplotlib.axes._subplots.AxesSubplot object at 0x7fd2363569d0>,        <matplotlib.axes._subplots.AxesSubplot object at 0x7fd23dbfba50>,        <matplotlib.axes._subplots.AxesSubplot object at 0x7fd23c54a810>],       [<matplotlib.axes._subplots.AxesSubplot object at 0x7fd26a1e8890>,        <matplotlib.axes._subplots.AxesSubplot object at 0x7fd23f1caa50>,        <matplotlib.axes._subplots.AxesSubplot object at 0x7fd23e856a10>,        <matplotlib.axes._subplots.AxesSubplot object at 0x7fd237556990>],       [<matplotlib.axes._subplots.AxesSubplot object at 0x7fd23759aad0>,        <matplotlib.axes._subplots.AxesSubplot object at 0x7fd23e57a890>,        <matplotlib.axes._subplots.AxesSubplot object at 0x7fd23e1af850>,        <matplotlib.axes._subplots.AxesSubplot object at 0x7fd237feea50>]], dtype=object)
_images/scatter_matrix_kde.png

Density Plot

New in version 0.8.0.

You can create density plots using theSeries.plot.kde() andDataFrame.plot.kde() methods.

In [83]:ser=pd.Series(np.random.randn(1000))In [84]:ser.plot.kde()Out[84]:<matplotlib.axes._subplots.AxesSubplotat0x7fd23e72b390>
_images/kde_plot.png

Andrews Curves

Andrews curves allow one to plot multivariate data as a large numberof curves that are created using the attributes of samples as coefficientsfor Fourier series. By coloring these curves differently for each classit is possible to visualize data clustering. Curves belonging to samplesof the same class will usually be closer together and form larger structures.

Note: The “Iris” dataset is availablehere.

In [85]:frompandas.tools.plottingimportandrews_curvesIn [86]:data=pd.read_csv('data/iris.data')In [87]:plt.figure()Out[87]:<matplotlib.figure.Figureat0x7fd23c49d250>In [88]:andrews_curves(data,'Name')Out[88]:<matplotlib.axes._subplots.AxesSubplotat0x7fd236e47690>
_images/andrews_curves.png

Parallel Coordinates

Parallel coordinates is a plotting technique for plotting multivariate data.It allows one to see clusters in data and to estimate other statistics visually.Using parallel coordinates points are represented as connected line segments.Each vertical line represents one attribute. One set of connected line segmentsrepresents one data point. Points that tend to cluster will appear closer together.

In [89]:frompandas.tools.plottingimportparallel_coordinatesIn [90]:data=pd.read_csv('data/iris.data')In [91]:plt.figure()Out[91]:<matplotlib.figure.Figureat0x7fd236c6b110>In [92]:parallel_coordinates(data,'Name')Out[92]:<matplotlib.axes._subplots.AxesSubplotat0x7fd236ea4290>
_images/parallel_coordinates.png

Lag Plot

Lag plots are used to check if a data set or time series is random. Randomdata should not exhibit any structure in the lag plot. Non-random structureimplies that the underlying data are not random.

In [93]:frompandas.tools.plottingimportlag_plotIn [94]:plt.figure()Out[94]:<matplotlib.figure.Figureat0x7fd23763c0d0>In [95]:data=pd.Series(0.1*np.random.rand(1000)+   ....:0.9*np.sin(np.linspace(-99*np.pi,99*np.pi,num=1000)))   ....:In [96]:lag_plot(data)Out[96]:<matplotlib.axes._subplots.AxesSubplotat0x7fd23e90fa90>
_images/lag_plot.png

Autocorrelation Plot

Autocorrelation plots are often used for checking randomness in time series.This is done by computing autocorrelations for data values at varying time lags.If time series is random, such autocorrelations should be near zero for any andall time-lag separations. If time series is non-random then one or more of theautocorrelations will be significantly non-zero. The horizontal lines displayedin the plot correspond to 95% and 99% confidence bands. The dashed line is 99%confidence band.

In [97]:frompandas.tools.plottingimportautocorrelation_plotIn [98]:plt.figure()Out[98]:<matplotlib.figure.Figureat0x7fd2365af690>In [99]:data=pd.Series(0.7*np.random.rand(1000)+   ....:0.3*np.sin(np.linspace(-9*np.pi,9*np.pi,num=1000)))   ....:In [100]:autocorrelation_plot(data)Out[100]:<matplotlib.axes._subplots.AxesSubplotat0x7fd2378f3f10>
_images/autocorrelation_plot.png

Bootstrap Plot

Bootstrap plots are used to visually assess the uncertainty of a statistic, suchas mean, median, midrange, etc. A random subset of a specified size is selectedfrom a data set, the statistic in question is computed for this subset and theprocess is repeated a specified number of times. Resulting plots and histogramsare what constitutes the bootstrap plot.

In [101]:frompandas.tools.plottingimportbootstrap_plotIn [102]:data=pd.Series(np.random.rand(1000))In [103]:bootstrap_plot(data,size=50,samples=500,color='grey')Out[103]:<matplotlib.figure.Figureat0x7fd23e7c6ed0>
_images/bootstrap_plot.png

RadViz

RadViz is a way of visualizing multi-variate data. It is based on a simplespring tension minimization algorithm. Basically you set up a bunch of points ina plane. In our case they are equally spaced on a unit circle. Each pointrepresents a single attribute. You then pretend that each sample in the data setis attached to each of these points by a spring, the stiffness of which isproportional to the numerical value of that attribute (they are normalized tounit interval). The point in the plane, where our sample settles to (where theforces acting on our sample are at an equilibrium) is where a dot representingour sample will be drawn. Depending on which class that sample belongs it willbe colored differently.

Note: The “Iris” dataset is availablehere.

In [104]:frompandas.tools.plottingimportradvizIn [105]:data=pd.read_csv('data/iris.data')In [106]:plt.figure()Out[106]:<matplotlib.figure.Figureat0x7fd236e39fd0>In [107]:radviz(data,'Name')Out[107]:<matplotlib.axes._subplots.AxesSubplotat0x7fd23e2b8910>
_images/radviz.png

Plot Formatting

Most plotting methods have a set of keyword arguments that control thelayout and formatting of the returned plot:

In [108]:plt.figure();ts.plot(style='k--',label='Series');
_images/series_plot_basic2.png

For each kind of plot (e.g.line,bar,scatter) any additional argumentskeywords are passed along to the corresponding matplotlib function(ax.plot(),ax.bar(),ax.scatter()). These can be usedto control additional styling, beyond what pandas provides.

Controlling the Legend

You may set thelegend argument toFalse to hide the legend, which isshown by default.

In [109]:df=pd.DataFrame(np.random.randn(1000,4),index=ts.index,columns=list('ABCD'))In [110]:df=df.cumsum()In [111]:df.plot(legend=False)Out[111]:<matplotlib.axes._subplots.AxesSubplotat0x7fd23c44f610>
_images/frame_plot_basic_noleg.png

Scales

You may passlogy to get a log-scale Y axis.

In [112]:ts=pd.Series(np.random.randn(1000),index=pd.date_range('1/1/2000',periods=1000))In [113]:ts=np.exp(ts.cumsum())In [114]:ts.plot(logy=True)Out[114]:<matplotlib.axes._subplots.AxesSubplotat0x7fd235664310>
_images/series_plot_logy.png

See also thelogx andloglog keyword arguments.

Plotting on a Secondary Y-axis

To plot data on a secondary y-axis, use thesecondary_y keyword:

In [115]:df.A.plot()Out[115]:<matplotlib.axes._subplots.AxesSubplotat0x7fd23623cbd0>In [116]:df.B.plot(secondary_y=True,style='g')Out[116]:<matplotlib.axes._subplots.AxesSubplotat0x7fd2363e1950>
_images/series_plot_secondary_y.png

To plot some columns in a DataFrame, give the column names to thesecondary_ykeyword:

In [117]:plt.figure()Out[117]:<matplotlib.figure.Figureat0x7fd235aac710>In [118]:ax=df.plot(secondary_y=['A','B'])In [119]:ax.set_ylabel('CD scale')Out[119]:<matplotlib.text.Textat0x7fd23def6a50>In [120]:ax.right_ax.set_ylabel('AB scale')Out[120]:<matplotlib.text.Textat0x7fd237aa4cd0>
_images/frame_plot_secondary_y.png

Note that the columns plotted on the secondary y-axis is automatically markedwith “(right)” in the legend. To turn off the automatic marking, use themark_right=False keyword:

In [121]:plt.figure()Out[121]:<matplotlib.figure.Figureat0x7fd237b49450>In [122]:df.plot(secondary_y=['A','B'],mark_right=False)Out[122]:<matplotlib.axes._subplots.AxesSubplotat0x7fd23c12bb90>
_images/frame_plot_secondary_y_no_right.png

Suppressing Tick Resolution Adjustment

pandas includes automatic tick resolution adjustment for regular frequencytime-series data. For limited cases where pandas cannot infer the frequencyinformation (e.g., in an externally createdtwinx), you can choose tosuppress this behavior for alignment purposes.

Here is the default behavior, notice how the x-axis tick labelling is performed:

In [123]:plt.figure()Out[123]:<matplotlib.figure.Figureat0x7fd2350ab1d0>In [124]:df.A.plot()Out[124]:<matplotlib.axes._subplots.AxesSubplotat0x7fd23c8b9790>
_images/ser_plot_suppress.png

Using thex_compat parameter, you can suppress this behavior:

In [125]:plt.figure()Out[125]:<matplotlib.figure.Figureat0x7fd23eaaa690>In [126]:df.A.plot(x_compat=True)Out[126]:<matplotlib.axes._subplots.AxesSubplotat0x7fd24013b750>
_images/ser_plot_suppress_parm.png

If you have more than one plot that needs to be suppressed, theuse methodinpandas.plot_params can be used in awith statement:

In [127]:plt.figure()Out[127]:<matplotlib.figure.Figureat0x7fd23eb9b850>In [128]:withpd.plot_params.use('x_compat',True):   .....:df.A.plot(color='r')   .....:df.B.plot(color='g')   .....:df.C.plot(color='b')   .....:
_images/ser_plot_suppress_context.png

Subplots

Each Series in a DataFrame can be plotted on a different axiswith thesubplots keyword:

In [129]:df.plot(subplots=True,figsize=(6,6));
_images/frame_plot_subplots.png

Using Layout and Targeting Multiple Axes

The layout of subplots can be specified bylayout keyword. It can accept(rows,columns). Thelayout keyword can be used inhist andboxplot also. If input is invalid,ValueError will be raised.

The number of axes which can be contained by rows x columns specified bylayout must belarger than the number of required subplots. If layout can contain more axes than required,blank axes are not drawn. Similar to a numpy array’sreshape method, youcan use-1 for one dimension to automatically calculate the number of rowsor columns needed, given the other.

In [130]:df.plot(subplots=True,layout=(2,3),figsize=(6,6),sharex=False);
_images/frame_plot_subplots_layout.png

The above example is identical to using

In [131]:df.plot(subplots=True,layout=(2,-1),figsize=(6,6),sharex=False);

The required number of columns (3) is inferred from the number of series to plotand the given number of rows (2).

Also, you can pass multiple axes created beforehand as list-like viaax keyword.This allows to use more complicated layout.The passed axes must be the same number as the subplots being drawn.

When multiple axes are passed viaax keyword,layout,sharex andsharey keywordsdon’t affect to the output. You should explicitly passsharex=False andsharey=False,otherwise you will see a warning.

In [132]:fig,axes=plt.subplots(4,4,figsize=(6,6));In [133]:plt.subplots_adjust(wspace=0.5,hspace=0.5);In [134]:target1=[axes[0][0],axes[1][1],axes[2][2],axes[3][3]]In [135]:target2=[axes[3][0],axes[2][1],axes[1][2],axes[0][3]]In [136]:df.plot(subplots=True,ax=target1,legend=False,sharex=False,sharey=False);In [137]:(-df).plot(subplots=True,ax=target2,legend=False,sharex=False,sharey=False);
_images/frame_plot_subplots_multi_ax.png

Another option is passing anax argument toSeries.plot() to plot on a particular axis:

In [138]:fig,axes=plt.subplots(nrows=2,ncols=2)In [139]:df['A'].plot(ax=axes[0,0]);axes[0,0].set_title('A');In [140]:df['B'].plot(ax=axes[0,1]);axes[0,1].set_title('B');In [141]:df['C'].plot(ax=axes[1,0]);axes[1,0].set_title('C');In [142]:df['D'].plot(ax=axes[1,1]);axes[1,1].set_title('D');
_images/series_plot_multi.png

Plotting With Error Bars

New in version 0.14.

Plotting with error bars is now supported in theDataFrame.plot() andSeries.plot()

Horizontal and vertical errorbars can be supplied to thexerr andyerr keyword arguments toplot(). The error values can be specified using a variety of formats.

  • As aDataFrame ordict of errors with column names matching thecolumns attribute of the plottingDataFrame or matching thename attribute of theSeries
  • As astr indicating which of the columns of plottingDataFrame contain the error values
  • As raw values (list,tuple, ornp.ndarray). Must be the same length as the plottingDataFrame/Series

Asymmetrical error bars are also supported, however raw error values must be provided in this case. For aM lengthSeries, aMx2 array should be provided indicating lower and upper (or left and right) errors. For aMxNDataFrame, asymmetrical errors should be in aMx2xN array.

Here is an example of one way to easily plot group means with standard deviations from the raw data.

# Generate the dataIn [143]:ix3=pd.MultiIndex.from_arrays([['a','a','a','a','b','b','b','b'],['foo','foo','bar','bar','foo','foo','bar','bar']],names=['letter','word'])In [144]:df3=pd.DataFrame({'data1':[3,2,4,3,2,4,3,2],'data2':[6,5,7,5,4,5,6,5]},index=ix3)# Group by index labels and take the means and standard deviations for each groupIn [145]:gp3=df3.groupby(level=('letter','word'))In [146]:means=gp3.mean()In [147]:errors=gp3.std()In [148]:meansOut[148]:             data1  data2letter worda      bar     3.5    6.0       foo     2.5    5.5b      bar     2.5    5.5       foo     3.0    4.5In [149]:errorsOut[149]:                data1     data2letter worda      bar   0.707107  1.414214       foo   0.707107  0.707107b      bar   0.707107  0.707107       foo   1.414214  0.707107# PlotIn [150]:fig,ax=plt.subplots()In [151]:means.plot.bar(yerr=errors,ax=ax)Out[151]:<matplotlib.axes._subplots.AxesSubplotat0x7fd23c5e97d0>
_images/errorbar_example.png

Plotting Tables

New in version 0.14.

Plotting with matplotlib table is now supported inDataFrame.plot() andSeries.plot() with atable keyword. Thetable keyword can acceptbool,DataFrame orSeries. The simple way to draw a table is to specifytable=True. Data will be transposed to meet matplotlib’s default layout.

In [152]:fig,ax=plt.subplots(1,1)In [153]:df=pd.DataFrame(np.random.rand(5,3),columns=['a','b','c'])In [154]:ax.get_xaxis().set_visible(False)# Hide TicksIn [155]:df.plot(table=True,ax=ax)Out[155]:<matplotlib.axes._subplots.AxesSubplotat0x7fd2360f4d90>
_images/line_plot_table_true.png

Also, you can pass differentDataFrame orSeries fortable keyword. The data will be drawn as displayed in print method (not transposed automatically). If required, it should be transposed manually as below example.

In [156]:fig,ax=plt.subplots(1,1)In [157]:ax.get_xaxis().set_visible(False)# Hide TicksIn [158]:df.plot(table=np.round(df.T,2),ax=ax)Out[158]:<matplotlib.axes._subplots.AxesSubplotat0x7fd23dde6d90>
_images/line_plot_table_data.png

Finally, there is a helper functionpandas.tools.plotting.table to create a table fromDataFrame andSeries, and add it to anmatplotlib.Axes. This function can accept keywords which matplotlib table has.

In [159]:frompandas.tools.plottingimporttableIn [160]:fig,ax=plt.subplots(1,1)In [161]:table(ax,np.round(df.describe(),2),   .....:loc='upper right',colWidths=[0.2,0.2,0.2])   .....:Out[161]:<matplotlib.table.Tableat0x7fd23ca8c950>In [162]:df.plot(ax=ax,ylim=(0,2),legend=None)Out[162]:<matplotlib.axes._subplots.AxesSubplotat0x7fd23e9951d0>
_images/line_plot_table_describe.png

Note: You can get table instances on the axes usingaxes.tables property for further decorations. See thematplotlib table documentation for more.

Colormaps

A potential issue when plotting a large number of columns is that it can bedifficult to distinguish some series due to repetition in the default colors. Toremedy this, DataFrame plotting supports the use of thecolormap= argument,which accepts either a Matplotlibcolormapor a string that is a name of a colormap registered with Matplotlib. Avisualization of the default matplotlib colormaps is availablehere.

As matplotlib does not directly support colormaps for line-based plots, thecolors are selected based on an even spacing determined by the number of columnsin the DataFrame. There is no consideration made for background color, so somecolormaps will produce lines that are not easily visible.

To use the cubehelix colormap, we can simply pass'cubehelix' tocolormap=

In [163]:df=pd.DataFrame(np.random.randn(1000,10),index=ts.index)In [164]:df=df.cumsum()In [165]:plt.figure()Out[165]:<matplotlib.figure.Figureat0x7fd234ee80d0>In [166]:df.plot(colormap='cubehelix')Out[166]:<matplotlib.axes._subplots.AxesSubplotat0x7fd2374f19d0>
_images/cubehelix.png

or we can pass the colormap itself

In [167]:frommatplotlibimportcmIn [168]:plt.figure()Out[168]:<matplotlib.figure.Figureat0x7fd23c990710>In [169]:df.plot(colormap=cm.cubehelix)Out[169]:<matplotlib.axes._subplots.AxesSubplotat0x7fd23dc944d0>
_images/cubehelix_cm.png

Colormaps can also be used other plot types, like bar charts:

In [170]:dd=pd.DataFrame(np.random.randn(10,10)).applymap(abs)In [171]:dd=dd.cumsum()In [172]:plt.figure()Out[172]:<matplotlib.figure.Figureat0x7fd23544f350>In [173]:dd.plot.bar(colormap='Greens')Out[173]:<matplotlib.axes._subplots.AxesSubplotat0x7fd23c09dad0>
_images/greens.png

Parallel coordinates charts:

In [174]:plt.figure()Out[174]:<matplotlib.figure.Figureat0x7fd235ffab50>In [175]:parallel_coordinates(data,'Name',colormap='gist_rainbow')Out[175]:<matplotlib.axes._subplots.AxesSubplotat0x7fd2353da890>
_images/parallel_gist_rainbow.png

Andrews curves charts:

In [176]:plt.figure()Out[176]:<matplotlib.figure.Figureat0x7fd22b679550>In [177]:andrews_curves(data,'Name',colormap='winter')Out[177]:<matplotlib.axes._subplots.AxesSubplotat0x7fd22b6aef50>
_images/andrews_curve_winter.png

Plotting directly with matplotlib

In some situations it may still be preferable or necessary to prepare plotsdirectly with matplotlib, for instance when a certain type of plot orcustomization is not (yet) supported by pandas. Series and DataFrame objectsbehave like arrays and can therefore be passed directly to matplotlib functionswithout explicit casts.

pandas also automatically registers formatters and locators that recognize dateindices, thereby extending date and time support to practically all plot typesavailable in matplotlib. Although this formatting does not provide the samelevel of refinement you would get when plotting via pandas, it can be fasterwhen plotting a large number of points.

Note

The speed up for large data sets only applies to pandas 0.14.0 and later.

In [178]:price=pd.Series(np.random.randn(150).cumsum(),   .....:index=pd.date_range('2000-1-1',periods=150,freq='B'))   .....:In [179]:ma=price.rolling(20).mean()In [180]:mstd=price.rolling(20).std()In [181]:plt.figure()Out[181]:<matplotlib.figure.Figureat0x7fd22b28a150>In [182]:plt.plot(price.index,price,'k')Out[182]:[<matplotlib.lines.Line2Dat0x7fd22b228b90>]In [183]:plt.plot(ma.index,ma,'b')Out[183]:[<matplotlib.lines.Line2Dat0x7fd22b27ba90>]In [184]:plt.fill_between(mstd.index,ma-2*mstd,ma+2*mstd,color='b',alpha=0.2)Out[184]:<matplotlib.collections.PolyCollectionat0x7fd22b191810>
_images/bollinger.png

Trellis plotting interface

Warning

Therplot trellis plotting interface has beenremoved. Please useexternal packages likeseaborn forsimilar but more refined functionality and refer to our 0.18.1 documentationherefor how to convert to using it.

Navigation

Scroll To Top
[8]ページ先頭

©2009-2025 Movatter.jp