error plotting series object from pandas library - python

I have encountered an error while working through Ch12 of the book Numerical Python: A Practical Techniques Approach for Industry (http://jrjohansson.github.io/numericalpython.html).
I am getting an error when I try to plot a series object using the pandas library.
So far the following lines of code have worked:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
pd.set_option('display.mpl_style', 'default')
s = pd.Series([909976, 8615246, 2872086, 2273305])
s
0 909976
1 8615246
2 2872086
3 2273305
dtype: int64
When I plot the series object s I get the following error:
AttributeError Traceback (most recent call last)
<ipython-input-81-d3eb09d34df4> in <module>()
----> 1 s.plot()
/anaconda/lib/python3.5/site-packages/pandas/tools/plotting.py in __call__(self, kind, ax, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, label, secondary_y, **kwds)
3495 colormap=colormap, table=table, yerr=yerr,
3496 xerr=xerr, label=label, secondary_y=secondary_y,
-> 3497 **kwds)
3498 __call__.__doc__ = plot_series.__doc__
3499
/anaconda/lib/python3.5/site-packages/pandas/tools/plotting.py in plot_series(data, kind, ax, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, label, secondary_y, **kwds)
2585 yerr=yerr, xerr=xerr,
2586 label=label, secondary_y=secondary_y,
-> 2587 **kwds)
2588
2589
/anaconda/lib/python3.5/site-packages/pandas/tools/plotting.py in _plot(data, x, y, subplots, ax, kind, **kwds)
2382 plot_obj = klass(data, subplots=subplots, ax=ax, kind=kind, **kwds)
2383
-> 2384 plot_obj.generate()
2385 plot_obj.draw()
2386 return plot_obj.result
/anaconda/lib/python3.5/site-packages/pandas/tools/plotting.py in generate(self)
985 self._compute_plot_data()
986 self._setup_subplots()
--> 987 self._make_plot()
988 self._add_table()
989 self._make_legend()
/anaconda/lib/python3.5/site-packages/pandas/tools/plotting.py in _make_plot(self)
1662 stacking_id=stacking_id,
1663 is_errorbar=is_errorbar,
-> 1664 **kwds)
1665 self._add_legend_handle(newlines[0], label, index=i)
1666
anaconda/lib/python3.5/site-packages/pandas/tools/plotting.py in _plot(cls, ax, x, y, style, column_num, stacking_id, **kwds)
1676 cls._initialize_stacker(ax, stacking_id, len(y))
1677 y_values = cls._get_stacked_values(ax, stacking_id, y, kwds['label'])
-> 1678 lines = MPLPlot._plot(ax, x, y_values, style=style, **kwds)
1679 cls._update_stacker(ax, stacking_id, y)
1680 return lines
/anaconda/lib/python3.5/site-packages/pandas/tools/plotting.py in _plot(cls, ax, x, y, style, is_errorbar, **kwds)
1298 else:
1299 args = (x, y)
-> 1300 return ax.plot(*args, **kwds)
1301
1302 def _get_index_name(self):
/anaconda/lib/python3.5/site-packages/matplotlib/__init__.py in inner(ax, *args, **kwargs)
1809 warnings.warn(msg % (label_namer, func.__name__),
1810 RuntimeWarning, stacklevel=2)
-> 1811 return func(ax, *args, **kwargs)
1812 pre_doc = inner.__doc__
1813 if pre_doc is None:
/anaconda/lib/python3.5/site-packages/matplotlib/axes/_axes.py in plot(self, *args, **kwargs)
1425 kwargs['color'] = c
1426
-> 1427 for line in self._get_lines(*args, **kwargs):
1428 self.add_line(line)
1429 lines.append(line)
/anaconda/lib/python3.5/site-packages/matplotlib/axes/_base.py in _grab_next_args(self, *args, **kwargs)
384 return
385 if len(remaining) <= 3:
--> 386 for seg in self._plot_args(remaining, kwargs):
387 yield seg
388 return
anaconda/lib/python3.5/site-packages/matplotlib/axes/_base.py in _plot_args(self, tup, kwargs)
372 ncx, ncy = x.shape[1], y.shape[1]
373 for j in xrange(max(ncx, ncy)):
--> 374 seg = func(x[:, j % ncx], y[:, j % ncy], kw, kwargs)
375 ret.append(seg)
376 return ret
/anaconda/lib/python3.5/site-packages/matplotlib/axes/_base.py in _makeline(self, x, y, kw, kwargs)
278 default_dict = self._getdefaults(None, kw, kwargs)
279 self._setdefaults(default_dict, kw, kwargs)
--> 280 seg = mlines.Line2D(x, y, **kw)
281 self.set_lineprops(seg, **kwargs)
282 return seg
/anaconda/lib/python3.5/site-packages/matplotlib/lines.py in __init__(self, xdata, ydata, linewidth, linestyle, color, marker, markersize, markeredgewidth, markeredgecolor, markerfacecolor, markerfacecoloralt, fillstyle, antialiased, dash_capstyle, solid_capstyle, dash_joinstyle, solid_joinstyle, pickradius, drawstyle, markevery, **kwargs)
364 # update kwargs before updating data to give the caller a
365 # chance to init axes (and hence unit support)
--> 366 self.update(kwargs)
367 self.pickradius = pickradius
368 self.ind_offset = 0
/anaconda/lib/python3.5/site-packages/matplotlib/artist.py in update(self, props)
854 func = getattr(self, 'set_' + k, None)
855 if func is None or not six.callable(func):
--> 856 raise AttributeError('Unknown property %s' % k)
857 func(v)
858 changed = True
AttributeError: Unknown property color_cycle
I have a 64 bit linux OS and the most recent anaconda installed.

Related

seaborn lmplot logistic raises AttributeError: module 'pandas' has no attribute 'Panel'

I am using the code below that I took from the Seaborn documentation as it is. Running this code results in an error.
AttributeError: module 'pandas' has no attribute 'Panel'
I am wondering if there is a way around this problem without reverting to a previous version of Pandas. Can anyone help?
tips = sns.load_dataset("tips")
tips["big_tip"] = (tips.tip / tips.total_bill) > .15
sns.lmplot(x="total_bill", y="big_tip", data=tips,
logistic=True, y_jitter=.03);
The version info as well as the complete error message are as follows:
pandas : 1.3.5
seaborn: '0.11.2'
--------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-4-2a96c34ef86c> in <module>
2 tips["big_tip"] = (tips.tip / tips.total_bill) > .15
3 sns.lmplot(x="total_bill", y="big_tip", data=tips,
----> 4 logistic=True, y_jitter=.03);
~/anaconda3/lib/python3.7/site-packages/seaborn/_decorators.py in inner_f(*args, **kwargs)
44 )
45 kwargs.update({k: arg for k, arg in zip(sig.parameters, args)})
---> 46 return f(**kwargs)
47 return inner_f
48
~/anaconda3/lib/python3.7/site-packages/seaborn/regression.py in lmplot(x, y, data, hue, col, row, palette, col_wrap, height, aspect, markers, sharex, sharey, hue_order, col_order, row_order, legend, legend_out, x_estimator, x_bins, x_ci, scatter, fit_reg, ci, n_boot, units, seed, order, logistic, lowess, robust, logx, x_partial, y_partial, truncate, x_jitter, y_jitter, scatter_kws, line_kws, facet_kws, size)
643 scatter_kws=scatter_kws, line_kws=line_kws,
644 )
--> 645 facets.map_dataframe(regplot, x=x, y=y, **regplot_kws)
646 facets.set_axis_labels(x, y)
647
~/anaconda3/lib/python3.7/site-packages/seaborn/axisgrid.py in map_dataframe(self, func, *args, **kwargs)
775
776 # Draw the plot
--> 777 self._facet_plot(func, ax, args, kwargs)
778
779 # For axis labels, prefer to use positional args for backcompat
~/anaconda3/lib/python3.7/site-packages/seaborn/axisgrid.py in _facet_plot(self, func, ax, plot_args, plot_kwargs)
804 plot_args = []
805 plot_kwargs["ax"] = ax
--> 806 func(*plot_args, **plot_kwargs)
807
808 # Sort out the supporting information
~/anaconda3/lib/python3.7/site-packages/seaborn/_decorators.py in inner_f(*args, **kwargs)
44 )
45 kwargs.update({k: arg for k, arg in zip(sig.parameters, args)})
---> 46 return f(**kwargs)
47 return inner_f
48
~/anaconda3/lib/python3.7/site-packages/seaborn/regression.py in regplot(x, y, data, x_estimator, x_bins, x_ci, scatter, fit_reg, ci, n_boot, units, seed, order, logistic, lowess, robust, logx, x_partial, y_partial, truncate, dropna, x_jitter, y_jitter, label, color, marker, scatter_kws, line_kws, ax)
861 scatter_kws["marker"] = marker
862 line_kws = {} if line_kws is None else copy.copy(line_kws)
--> 863 plotter.plot(ax, scatter_kws, line_kws)
864 return ax
865
~/anaconda3/lib/python3.7/site-packages/seaborn/regression.py in plot(self, ax, scatter_kws, line_kws)
368
369 if self.fit_reg:
--> 370 self.lineplot(ax, line_kws)
371
372 # Label the axes
~/anaconda3/lib/python3.7/site-packages/seaborn/regression.py in lineplot(self, ax, kws)
411 """Draw the model."""
412 # Fit the regression model
--> 413 grid, yhat, err_bands = self.fit_regression(ax)
414 edges = grid[0], grid[-1]
415
~/anaconda3/lib/python3.7/site-packages/seaborn/regression.py in fit_regression(self, ax, x_range, grid)
209 from statsmodels.genmod.families import Binomial
210 yhat, yhat_boots = self.fit_statsmodels(grid, GLM,
--> 211 family=Binomial())
212 elif self.lowess:
213 ci = None
~/anaconda3/lib/python3.7/site-packages/seaborn/regression.py in fit_statsmodels(self, grid, model, **kwargs)
279 return yhat
280
--> 281 yhat = reg_func(X, y)
282 if self.ci is None:
283 return yhat, None
~/anaconda3/lib/python3.7/site-packages/seaborn/regression.py in reg_func(_x, _y)
273 def reg_func(_x, _y):
274 try:
--> 275 yhat = model(_y, _x, **kwargs).fit().predict(grid)
276 except glm.PerfectSeparationError:
277 yhat = np.empty(len(grid))
~/anaconda3/lib/python3.7/site-packages/statsmodels/genmod/generalized_linear_model.py in __init__(self, endog, exog, family, offset, exposure, freq_weights, var_weights, missing, **kwargs)
289 offset=offset, exposure=exposure,
290 freq_weights=freq_weights,
--> 291 var_weights=var_weights, **kwargs)
292 self._check_inputs(family, self.offset, self.exposure, self.endog,
293 self.freq_weights, self.var_weights)
~/anaconda3/lib/python3.7/site-packages/statsmodels/base/model.py in __init__(self, endog, exog, **kwargs)
214
215 def __init__(self, endog, exog=None, **kwargs):
--> 216 super(LikelihoodModel, self).__init__(endog, exog, **kwargs)
217 self.initialize()
218
~/anaconda3/lib/python3.7/site-packages/statsmodels/base/model.py in __init__(self, endog, exog, **kwargs)
66 hasconst = kwargs.pop('hasconst', None)
67 self.data = self._handle_data(endog, exog, missing, hasconst,
---> 68 **kwargs)
69 self.k_constant = self.data.k_constant
70 self.exog = self.data.exog
~/anaconda3/lib/python3.7/site-packages/statsmodels/base/model.py in _handle_data(self, endog, exog, missing, hasconst, **kwargs)
89
90 def _handle_data(self, endog, exog, missing, hasconst, **kwargs):
---> 91 data = handle_data(endog, exog, missing, hasconst, **kwargs)
92 # kwargs arrays could have changed, easier to just attach here
93 for key in kwargs:
~/anaconda3/lib/python3.7/site-packages/statsmodels/base/data.py in handle_data(endog, exog, missing, hasconst, **kwargs)
631 exog = np.asarray(exog)
632
--> 633 klass = handle_data_class_factory(endog, exog)
634 return klass(endog, exog=exog, missing=missing, hasconst=hasconst,
635 **kwargs)
~/anaconda3/lib/python3.7/site-packages/statsmodels/base/data.py in handle_data_class_factory(endog, exog)
611 if data_util._is_using_ndarray_type(endog, exog):
612 klass = ModelData
--> 613 elif data_util._is_using_pandas(endog, exog):
614 klass = PandasData
615 elif data_util._is_using_patsy(endog, exog):
~/anaconda3/lib/python3.7/site-packages/statsmodels/tools/data.py in _is_using_pandas(endog, exog)
99
100 def _is_using_pandas(endog, exog):
--> 101 from statsmodels.compat.pandas import data_klasses as klasses
102 return (isinstance(endog, klasses) or isinstance(exog, klasses))
103
~/anaconda3/lib/python3.7/site-packages/statsmodels/compat/pandas.py in <module>
21 except ImportError:
22 from pandas.tseries import frequencies
---> 23 data_klasses = (pandas.Series, pandas.DataFrame, pandas.Panel)
24 else:
25 try:
~/anaconda3/lib/python3.7/site-packages/pandas/__init__.py in __getattr__(name)
242 return _SparseArray
243
--> 244 raise AttributeError(f"module 'pandas' has no attribute '{name}'")
245
246
AttributeError: module 'pandas' has no attribute 'Panel'
you are using the latest version of pandas library where Panal is removed from pandas version 0.25 and onward

matplotlib.pyplot.hist() attribute error

I am quite new to python and computer science in general, so maybe I'm missing something obvious, but I would greatly appreciate it if someone could point it out!
I can't figure out what happened to my pyplot histogram function.
Independent of the list it is asked to plot it returns an Attribute Error. Does anyone know how I can fix this?
When running:
import matplotlib.pyplot as plt
import numpy as np
test = [np.random.randn() for i in range(100)]
plt.hist(test)
plt.show()
It returns:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-268-b26700f187c9> in <module>()
5 test = [np.random.randn() for i in range(10**3)]
6
----> 7 plt.hist(test)
8 plt.show()
c:\users\wiepvandertoorn\appdata\local\programs\python\python36\lib\site-packages\matplotlib\pyplot.py in hist(x, bins, range, density, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, normed, hold, data, **kwargs)
3002 histtype=histtype, align=align, orientation=orientation,
3003 rwidth=rwidth, log=log, color=color, label=label,
-> 3004 stacked=stacked, normed=normed, data=data, **kwargs)
3005 finally:
3006 ax._hold = washold
c:\users\wiepvandertoorn\appdata\local\programs\python\python36\lib\site-packages\matplotlib\__init__.py in inner(ax, *args, **kwargs)
1708 warnings.warn(msg % (label_namer, func.__name__),
1709 RuntimeWarning, stacklevel=2)
-> 1710 return func(ax, *args, **kwargs)
1711 pre_doc = inner.__doc__
1712 if pre_doc is None:
c:\users\wiepvandertoorn\appdata\local\programs\python\python36\lib\site-packages\matplotlib\axes\_axes.py in hist(***failed resolving arguments***)
6284 patch = _barfunc(bins[:-1]+boffset, height, width,
6285 align='center', log=log,
-> 6286 color=c, **{bottom_kwarg: bottom})
6287 patches.append(patch)
6288 if stacked:
c:\users\wiepvandertoorn\appdata\local\programs\python\python36\lib\site-packages\matplotlib\__init__.py in inner(ax, *args, **kwargs)
1708 warnings.warn(msg % (label_namer, func.__name__),
1709 RuntimeWarning, stacklevel=2)
-> 1710 return func(ax, *args, **kwargs)
1711 pre_doc = inner.__doc__
1712 if pre_doc is None:
c:\users\wiepvandertoorn\appdata\local\programs\python\python36\lib\site-packages\matplotlib\axes\_axes.py in bar(self, *args, **kwargs)
2118
2119 if self.yaxis is not None:
-> 2120 y = self.convert_yunits(y)
2121 height = self.convert_yunits(height)
2122 if yerr is not None:
c:\users\wiepvandertoorn\appdata\local\programs\python\python36\lib\site-packages\matplotlib\artist.py in convert_yunits(self, y)
198 if ax is None or ax.yaxis is None:
199 return y
--> 200 return ax.yaxis.convert_units(y)
201
202 #property
c:\users\wiepvandertoorn\appdata\local\programs\python\python36\lib\site-packages\matplotlib\axis.py in convert_units(self, x)
1489 return x
1490
-> 1491 ret = self.converter.convert(x, self.units, self)
1492 return ret
1493
c:\users\wiepvandertoorn\appdata\local\programs\python\python36\lib\site-packages\matplotlib\category.py in convert(value, unit, axis)
41 data as floats
42 """
---> 43 vmap = dict(zip(axis.unit_data.seq, axis.unit_data.locs))
44
45 if isinstance(value, six.string_types):
AttributeError: 'NoneType' object has no attribute 'seq'

Why do I get NonGuiException in jupyter notebook when trying to plot using matplotlib inline?

I get an error when trying to plot inline in a jupyter notebook.
%matplotlib inline
N = 20
M = 10
df = pd.DataFrame(
index=pd.date_range(dtt.date.today(), periods=N),
data=np.random.randn(N, M),
columns=['path_{}'.format(ii) for ii in range(M)]
)
df.plot()
I get the following NonGuiException error. Even though the image plots it seems to raise an exception. If as the index to the dataframe I use range(N) it works just fine which is strange.
Any ideas what is going on?
--------------------------------------------------------------------------- NonGuiException Traceback (most recent call last) in ()
6 columns=['path_{}'.format(ii) for ii in range(M)]
7 )
----> 8 df.plot()
/usr/local/lib/python3.5/dist-packages/pandas/tools/plotting.py in
__call__(self, x, y, kind, ax, subplots, sharex, sharey, layout, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, secondary_y, sort_columns, **kwds) 3771 fontsize=fontsize, colormap=colormap, table=table, 3772 yerr=yerr, xerr=xerr, secondary_y=secondary_y,
-> 3773 sort_columns=sort_columns, **kwds) 3774 __call__.__doc__ = plot_frame.__doc__ 3775
/usr/local/lib/python3.5/dist-packages/pandas/tools/plotting.py in plot_frame(data, x, y, kind, ax, subplots, sharex, sharey, layout, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, secondary_y, sort_columns, **kwds) 2640 yerr=yerr, xerr=xerr, 2641 secondary_y=secondary_y, sort_columns=sort_columns,
-> 2642 **kwds) 2643 2644
/usr/local/lib/python3.5/dist-packages/pandas/tools/plotting.py in
_plot(data, x, y, subplots, ax, kind, **kwds) 2467 plot_obj = klass(data, subplots=subplots, ax=ax, kind=kind, **kwds) 2468
-> 2469 plot_obj.generate() 2470 plot_obj.draw() 2471 return plot_obj.result
/usr/local/lib/python3.5/dist-packages/pandas/tools/plotting.py in generate(self) 1041 self._compute_plot_data() 1042 self._setup_subplots()
-> 1043 self._make_plot() 1044 self._add_table() 1045 self._make_legend()
/usr/local/lib/python3.5/dist-packages/pandas/tools/plotting.py in
_make_plot(self) 1724 stacking_id=stacking_id, 1725 is_errorbar=is_errorbar,
-> 1726 **kwds) 1727 self._add_legend_handle(newlines[0], label, index=i) 1728
/usr/local/lib/python3.5/dist-packages/pandas/tools/plotting.py in
_ts_plot(cls, ax, x, data, style, **kwds) 1764 lines = cls._plot(ax, data.index, data.values, style=style, **kwds) 1765
# set date formatter, locators and rescale limits
-> 1766 format_dateaxis(ax, ax.freq) 1767 return lines 1768
/usr/local/lib/python3.5/dist-packages/pandas/tseries/plotting.py in format_dateaxis(subplot, freq)
292 "t = {0} y = {1:8f}".format(Period(ordinal=int(t), freq=freq), y))
293
--> 294 pylab.draw_if_interactive()
/usr/local/lib/python3.5/dist-packages/IPython/utils/decorators.py in wrapper(*args, **kw)
41 def wrapper(*args,**kw):
42 wrapper.called = False
---> 43 out = func(*args,**kw)
44 wrapper.called = True
45 return out
/usr/lib/python3/dist-packages/matplotlib/backends/backend_tkagg.py in draw_if_interactive()
68 figManager = Gcf.get_active()
69 if figManager is not None:
---> 70 figManager.show()
71
72 class Show(ShowBase):
/usr/lib/python3/dist-packages/matplotlib/backend_bases.py in show(self) 2618 optional warning. 2619 """
-> 2620 raise NonGuiException() 2621 2622 def destroy(self):
NonGuiException:
The command %matplotlib inline sets the backend. Check you haven't set a conflicting backend somewhere else.
I found that I had set my MPLBACKEND environment variable to TkAgg. As soon as I deleted it from my pipenv .env file and restarted my shell and Jupyter notebook server, inline ploting worked again.

Pandas 0.19: Attribute error "unknown property color_cycle" still exists while performing boxplot

Unlike what has been said here, the AttributeError: Unknown property color_cycle is still persistent in the newest Pandas version (0.19.0-1).
In my case, I have a dataframe similar to this, although much longer (3,000,000 rows):
A B C
1 05010001 17 1
2 05020001 5 1
3 05020002 11 1
4 05020003 2 1
5 05030001 86 1
6 07030001 84 2
7 07030002 10 2
8 08010001 16 3
For some reason, if I implement this very example, there are no errors. In my actual case, executing the simple
df.boxplot(by='C')
triggers this mess:
AttributeError Traceback (most recent call last)
<ipython-input-51-5c645348f82f> in <module>()
----> 1 df.boxplot(by='C')
C:\Users\B4058846\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\core\frame.pyc in boxplot(self, column, by, ax, fontsize, rot, grid, figsize, layout, return_type, **kwds)
5514
5515 columns = list(data.dtype.names)
-> 5516 arrays = [data[k] for k in columns]
5517 return arrays, columns
5518 else:
C:\Users\B4058846\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\tools\plotting.pyc in boxplot(data, column, by, ax, fontsize, rot, grid, figsize, layout, return_type, **kwds)
2687 ax : Matplotlib axes object, optional
2688 fontsize : int or string
-> 2689 rot : label rotation angle
2690 figsize : A tuple (width, height) in inches
2691 grid : Setting this to True will show the grid
C:\Users\B4058846\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\tools\plotting.pyc in _grouped_plot_by_column(plotf, data, columns, by, numeric_only, grid, figsize, ax, layout, return_type, **kwargs)
3091 >>> df = pandas.DataFrame(data, columns=list('ABCD'), index=index)
3092 >>>
-> 3093 >>> grouped = df.groupby(level='lvl1')
3094 >>> boxplot_frame_groupby(grouped)
3095 >>>
C:\Users\B4058846\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\tools\plotting.pyc in plot_group(keys, values, ax)
2659 create a figure with the default figsize, causing the figsize=parameter to
2660 be ignored.
-> 2661 """
2662 if ax is None and len(plt.get_fignums()) > 0:
2663 ax = _gca()
C:\Users\B4058846\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\__init__.pyc in inner(ax, *args, **kwargs)
1810 warnings.warn(msg % (label_namer, func.__name__),
1811 RuntimeWarning, stacklevel=2)
-> 1812 return func(ax, *args, **kwargs)
1813 pre_doc = inner.__doc__
1814 if pre_doc is None:
C:\Users\B4058846\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\axes\_axes.pyc in boxplot(self, x, notch, sym, vert, whis, positions, widths, patch_artist, bootstrap, usermedians, conf_intervals, meanline, showmeans, showcaps, showbox, showfliers, boxprops, labels, flierprops, medianprops, meanprops, capprops, whiskerprops, manage_xticks)
3321 meanline=meanline, showfliers=showfliers,
3322 capprops=capprops, whiskerprops=whiskerprops,
-> 3323 manage_xticks=manage_xticks)
3324 return artists
3325
C:\Users\B4058846\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\axes\_axes.pyc in bxp(self, bxpstats, positions, widths, vert, patch_artist, shownotches, showmeans, showcaps, showbox, showfliers, boxprops, whiskerprops, flierprops, medianprops, capprops, meanprops, meanline, manage_xticks)
3650 boxes.extend(dopatch(box_x, box_y, **final_boxprops))
3651 else:
-> 3652 boxes.extend(doplot(box_x, box_y, **final_boxprops))
3653
3654 # draw the whiskers
C:\Users\B4058846\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\axes\_axes.pyc in doplot(*args, **kwargs)
3564 if vert:
3565 def doplot(*args, **kwargs):
-> 3566 return self.plot(*args, **kwargs)
3567
3568 def dopatch(xs, ys, **kwargs):
C:\Users\B4058846\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\__init__.pyc in inner(ax, *args, **kwargs)
1810 warnings.warn(msg % (label_namer, func.__name__),
1811 RuntimeWarning, stacklevel=2)
-> 1812 return func(ax, *args, **kwargs)
1813 pre_doc = inner.__doc__
1814 if pre_doc is None:
C:\Users\B4058846\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\axes\_axes.pyc in plot(self, *args, **kwargs)
1422 kwargs['color'] = c
1423
-> 1424 for line in self._get_lines(*args, **kwargs):
1425 self.add_line(line)
1426 lines.append(line)
C:\Users\B4058846\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\axes\_base.pyc in _grab_next_args(self, *args, **kwargs)
384 return
385 if len(remaining) <= 3:
--> 386 for seg in self._plot_args(remaining, kwargs):
387 yield seg
388 return
C:\Users\B4058846\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\axes\_base.pyc in _plot_args(self, tup, kwargs)
372 ncx, ncy = x.shape[1], y.shape[1]
373 for j in xrange(max(ncx, ncy)):
--> 374 seg = func(x[:, j % ncx], y[:, j % ncy], kw, kwargs)
375 ret.append(seg)
376 return ret
C:\Users\B4058846\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\axes\_base.pyc in _makeline(self, x, y, kw, kwargs)
278 default_dict = self._getdefaults(None, kw, kwargs)
279 self._setdefaults(default_dict, kw, kwargs)
--> 280 seg = mlines.Line2D(x, y, **kw)
281 self.set_lineprops(seg, **kwargs)
282 return seg
C:\Users\B4058846\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\lines.pyc in __init__(self, xdata, ydata, linewidth, linestyle, color, marker, markersize, markeredgewidth, markeredgecolor, markerfacecolor, markerfacecoloralt, fillstyle, antialiased, dash_capstyle, solid_capstyle, dash_joinstyle, solid_joinstyle, pickradius, drawstyle, markevery, **kwargs)
365 # update kwargs before updating data to give the caller a
366 # chance to init axes (and hence unit support)
--> 367 self.update(kwargs)
368 self.pickradius = pickradius
369 self.ind_offset = 0
C:\Users\B4058846\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\artist.pyc in update(self, props)
854 func = getattr(self, 'set_' + k, None)
855 if func is None or not six.callable(func):
--> 856 raise AttributeError('Unknown property %s' % k)
857 func(v)
858 changed = True
AttributeError: Unknown property color_cycle
And I am left with a blank 4-pane plot, when there should have been just one with 5 boxplot columns:
How to fix this?
I've verified myself that one needs to have pandas 0.19.0-1 together with matplotlib 1.5.1-8 to not experience this error.

Keyerror in matplotlib when the column clearly exists

I'm trying to plot using the following code:
df.plot(kind='scatter',x='branch', y='retention', s=df['active_users']*200)
Which gives me the following error:
KeyError Traceback (most recent call last)
<ipython-input-17-e43e5aeff662> in <module>()
3 df = Flexbooks[Flexbooks['schoolyearsemester'] == StartSem][Flexbooks['branch'] != 'OTHE'][Flexbooks['branch'] != 'SSCI'][Flexbooks['branch'] != 'EM1'][Flexbooks['branch'] != 'EM2'][Flexbooks['branch'] != 'EM3'][Flexbooks['branch'] != 'EM4'][Flexbooks['branch'] != 'EM5'][Flexbooks['branch'] != 'SATP'][Flexbooks['branch'] != 'MORE'][Flexbooks['branch'] != 'SPEL'][Flexbooks['branch'] != 'ENG'][Flexbooks['branch'] != 'ENGG'][Flexbooks['branch'] != 'NANO'][Flexbooks['branch'] != 'TECH'][Flexbooks['branch'] != 'HIST'][Flexbooks['branch'] != 'WRIT'][Flexbooks['branch'] != 'ASTR'][Flexbooks['branch'] != 'EXAP']
4
----> 5 df.plot(kind='scatter',x='branch', y='retention', s=df['active_users']*200)
6 #df.plot.scatter(x='branch', y='retention', s=df['active_users']*200)
E:\Anaconda2\lib\site-packages\pandas\tools\plotting.pyc in __call__(self, x, y, kind, ax, subplots, sharex, sharey, layout, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, secondary_y, sort_columns, **kwds)
3669 fontsize=fontsize, colormap=colormap, table=table,
3670 yerr=yerr, xerr=xerr, secondary_y=secondary_y,
-> 3671 sort_columns=sort_columns, **kwds)
3672 __call__.__doc__ = plot_frame.__doc__
3673
E:\Anaconda2\lib\site-packages\pandas\tools\plotting.pyc in plot_frame(data, x, y, kind, ax, subplots, sharex, sharey, layout, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, secondary_y, sort_columns, **kwds)
2554 yerr=yerr, xerr=xerr,
2555 secondary_y=secondary_y, sort_columns=sort_columns,
-> 2556 **kwds)
2557
2558
E:\Anaconda2\lib\site-packages\pandas\tools\plotting.pyc in _plot(data, x, y, subplots, ax, kind, **kwds)
2382 plot_obj = klass(data, subplots=subplots, ax=ax, kind=kind, **kwds)
2383
-> 2384 plot_obj.generate()
2385 plot_obj.draw()
2386 return plot_obj.result
E:\Anaconda2\lib\site-packages\pandas\tools\plotting.pyc in generate(self)
985 self._compute_plot_data()
986 self._setup_subplots()
--> 987 self._make_plot()
988 self._add_table()
989 self._make_legend()
E:\Anaconda2\lib\site-packages\pandas\tools\plotting.pyc in _make_plot(self)
1556 else:
1557 label = None
-> 1558 scatter = ax.scatter(data[x].values, data[y].values, c=c_values,
1559 label=label, cmap=cmap, **self.kwds)
1560 if cb:
E:\Anaconda2\lib\site-packages\pandas\core\frame.pyc in __getitem__(self, key)
1967 return self._getitem_multilevel(key)
1968 else:
-> 1969 return self._getitem_column(key)
1970
1971 def _getitem_column(self, key):
E:\Anaconda2\lib\site-packages\pandas\core\frame.pyc in _getitem_column(self, key)
1974 # get column
1975 if self.columns.is_unique:
-> 1976 return self._get_item_cache(key)
1977
1978 # duplicate columns & possible reduce dimensionality
E:\Anaconda2\lib\site-packages\pandas\core\generic.pyc in _get_item_cache(self, item)
1089 res = cache.get(item)
1090 if res is None:
-> 1091 values = self._data.get(item)
1092 res = self._box_item_values(item, values)
1093 cache[item] = res
E:\Anaconda2\lib\site-packages\pandas\core\internals.pyc in get(self, item, fastpath)
3209
3210 if not isnull(item):
-> 3211 loc = self.items.get_loc(item)
3212 else:
3213 indexer = np.arange(len(self.items))[isnull(self.items)]
E:\Anaconda2\lib\site-packages\pandas\core\index.pyc in get_loc(self, key, method, tolerance)
1757 'backfill or nearest lookups')
1758 key = _values_from_object(key)
-> 1759 return self._engine.get_loc(key)
1760
1761 indexer = self.get_indexer([key], method=method,
pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:3979)()
pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:3843)()
pandas\hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12265)()
pandas\hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12216)()
KeyError: 'branch'
I can confidently say that the column 'branch' exists, then why the KeyError?
I know this problem exists when the column in datetime, but this column is string.
Any help would be appreciated.

Categories

Resources