This question already has an answer here:
How to add individual vlines to every subplot of seaborn FacetGrid
(1 answer)
Closed 1 year ago.
I have the following plot code in seaborn
import seaborn as sns
import matplotlib.pyplot as plt
iris= sns.load_dataset("iris")
g= sns.pairplot(iris,
x_vars=["sepal_width", "sepal_length"],
y_vars=["petal_width"])
This produces the following output
Now I am trying to add a vertical line at x=3 on both plots
I have tried using plt.axvline(x=3, ls='--', linewidth=3, color='red') however that draws the line only on the last plot, as shown below
How can I have the vertical line drawn on both plots?
I have tried g.map_offdiag(plt.axvline(x=1, ls='--', linewidth=3, color='red')) and the g.map() variant, however I get the following error.
TypeError Traceback (most recent call last)
<ipython-input-12-612fcf2a7fef> in <module>
9
10 # plt.axvline(x=3, ls='--', linewidth=3, color='red')
---> 11 g.map_offdiag(plt.axvline(x=1, ls='--', linewidth=3, color='red'))
12
13
~/PycharmProjects/venv/lib/python3.8/site-packages/seaborn/axisgrid.py in map_offdiag(self, func, **kwargs)
1318 if x_var != y_var:
1319 indices.append((i, j))
-> 1320 self._map_bivariate(func, indices, **kwargs)
1321 return self
1322
~/PycharmProjects/venv/lib/python3.8/site-packages/seaborn/axisgrid.py in _map_bivariate(self, func, indices, **kwargs)
1463 if ax is None: # i.e. we are in corner mode
1464 continue
-> 1465 self._plot_bivariate(x_var, y_var, ax, func, **kws)
1466 self._add_axis_labels()
1467
~/PycharmProjects/venv/lib/python3.8/site-packages/seaborn/axisgrid.py in _plot_bivariate(self, x_var, y_var, ax, func, **kwargs)
1471 def _plot_bivariate(self, x_var, y_var, ax, func, **kwargs):
1472 """Draw a bivariate plot on the specified axes."""
-> 1473 if "hue" not in signature(func).parameters:
1474 self._plot_bivariate_iter_hue(x_var, y_var, ax, func, **kwargs)
1475 return
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/inspect.py in signature(obj, follow_wrapped)
3091 def signature(obj, *, follow_wrapped=True):
3092 """Get a signature object for the passed callable."""
-> 3093 return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
3094
3095
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/inspect.py in from_callable(cls, obj, follow_wrapped)
2840 def from_callable(cls, obj, *, follow_wrapped=True):
2841 """Constructs Signature for the given callable object."""
-> 2842 return _signature_from_callable(obj, sigcls=cls,
2843 follow_wrapper_chains=follow_wrapped)
2844
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/inspect.py in _signature_from_callable(obj, follow_wrapper_chains, skip_bound_arg, sigcls)
2214
2215 if not callable(obj):
-> 2216 raise TypeError('{!r} is not a callable object'.format(obj))
2217
2218 if isinstance(obj, types.MethodType):
TypeError: <matplotlib.lines.Line2D object at 0x1287cc580> is not a callable object
Any suggestions?
The easiest way is to loop through the axes and call axvline() on each of them. Note that .ravel() converts the 2D array of axes to a 1D array.
import seaborn as sns
import matplotlib.pyplot as plt
iris = sns.load_dataset("iris")
g = sns.pairplot(iris,
x_vars=["sepal_width", "sepal_length"],
y_vars=["petal_width"])
for ax in g.axes.ravel():
ax.axvline(x=3, ls='--', linewidth=3, c='red')
plt.show()
To use g.map() or its variants, the first parameter needs to be a function (without calling), followed by the parameters. So, in theory it would be g.map(plt.axvline, x=1, ls='--', linewidth=3, color='red'). But for a pairplot, the mapped function gets called with an x and y parameter from the pairplot, which conflict with the x as parameter for axvline.
Related
What am I doing wrong here? I have tried to see if the shape of ydata and t are the same and they are in fact the same. The only thing that works is when I slice the output of the integrate.odeint function using [:,1] to give me the curve fit of didt. But the thing is, I require all three curves because I plan on graphing all three results. Your help is greatly appreciated.
import pandas as pd
import numpy as np
from datetime import datetime
from scipy import optimize
from scipy import integrate
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
N0=10203134 #susceptible population
ydata=np.array(df_plot.Jordan[253:]) #beginning on 1/10/2020
t=np.arange(len(ydata))
I0=ydata[0] #initial conditions
R0=4821
S0=N0-I0-R0
def SIR_Model(SIR,t,beta,alpha):
S,I,R=SIR
dsdt=-beta*S*I/N0
didt=beta*S*I/N0 -alpha*I
drdt=alpha*I
return dsdt,didt,drdt
def fit_ode(x,beta,alpha):
return integrate.odeint(SIR_Model,(S0,I0,R0),t,args=(beta,alpha))
print(ydata.shape)
print(t.shape)
popt,pcov=optimize.curve_fit(fit_ode,t,ydata)
perr=np.sqrt(np.diag(pcov))
print("standard deviation errors:",str(perr))
print("Optimal Parameters: Beta=",popt[0], "alpha:",popt[1])
ValueError Traceback (most recent call last)
<ipython-input-194-aa1bb286dbba> in <module>
----> 1 popt,pcov=optimize.curve_fit(fit_ode,t,ydata)
2 perr=np.sqrt(np.diag(pcov))
3 print("standard deviation errors:",str(perr))
4 print("Optimal Parameters: Beta=",popt[0], "alpha:",popt[1])
5
C:\ProgramData\Anaconda3\lib\site-packages\scipy\optimize\minpack.py in curve_fit(f, xdata, ydata, p0, sigma, absolute_sigma, check_finite, bounds, method, jac, **kwargs)
782 # Remove full_output from kwargs, otherwise we're passing it in twice.
783 return_full = kwargs.pop('full_output', False)
--> 784 res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs)
785 popt, pcov, infodict, errmsg, ier = res
786 ysize = len(infodict['fvec'])
C:\ProgramData\Anaconda3\lib\site-packages\scipy\optimize\minpack.py in leastsq(func, x0, args, Dfun, full_output, col_deriv, ftol, xtol, gtol, maxfev, epsfcn, factor, diag)
408 if not isinstance(args, tuple):
409 args = (args,)
--> 410 shape, dtype = _check_func('leastsq', 'func', func, x0, args, n)
411 m = shape[0]
412
C:\ProgramData\Anaconda3\lib\site-packages\scipy\optimize\minpack.py in _check_func(checker, argname, thefunc, x0, args, numinputs, output_shape)
22 def _check_func(checker, argname, thefunc, x0, args, numinputs,
23 output_shape=None):
---> 24 res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
25 if (output_shape is not None) and (shape(res) != output_shape):
26 if (output_shape[0] != 1):
C:\ProgramData\Anaconda3\lib\site-packages\scipy\optimize\minpack.py in func_wrapped(params)
482 if transform is None:
483 def func_wrapped(params):
--> 484 return func(xdata, *params) - ydata
485 elif transform.ndim == 1:
486 def func_wrapped(params):
ValueError: operands could not be broadcast together with shapes (138,3) (138,)
I'm trying to create single arrows at a time (i.e. just showing a wind vector at one location) using plt.quiver on a map. However, using when doing so (by using the ccrs.PlateCarree() transform) I get an issue where some sub-function is trying to get the number of dims of the 0-dim array / int.
Here's some minimal working examples:
from matplotlib import pyplot as plt
import cartopy
import cartopy.crs as ccrs
%matplotlib inline
#### Works: simple quiver plot
plt.quiver(0,0,1,-1)
#### Works: simple quiver plot on a map axis, without specifying transform (this obviously would get the location wrong, but just to show what works/doesn't)
plt.subplot(projection=ccrs.EckertIV())
plt.quiver(0,0,1,-1)
#### Works: simple quiver plot on a map axis with some other transform
plt.subplot(projection=ccrs.EckertIV())
plt.quiver(0,0,1,-1,transform=ccrs.EckertIV())
#### Doesn't work: simple quiver plot on a map axis with the PlateCarree transform
plt.subplot(projection=ccrs.EckertIV())
plt.quiver(0,0,1,-1,transform=ccrs.PlateCarree())
This last call produces the following error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-93-dec36b09994d> in <module>
1 plt.subplot(projection=ccrs.EckertIV())
----> 2 plt.quiver(0,0,1,-1,transform=ccrs.PlateCarree())
~/.conda/envs/climate1/lib/python3.7/site-packages/matplotlib/pyplot.py in quiver(data, *args, **kw)
2791 def quiver(*args, data=None, **kw):
2792 __ret = gca().quiver(
-> 2793 *args, **({"data": data} if data is not None else {}), **kw)
2794 sci(__ret)
2795 return __ret
~/.conda/envs/climate1/lib/python3.7/site-packages/cartopy/mpl/geoaxes.py in wrapper(self, *args, **kwargs)
308
309 kwargs['transform'] = transform
--> 310 return func(self, *args, **kwargs)
311 return wrapper
312
~/.conda/envs/climate1/lib/python3.7/site-packages/cartopy/mpl/geoaxes.py in quiver(self, x, y, u, v, *args, **kwargs)
1837 # Transform the vectors if the projection is not the same as the
1838 # data transform.
-> 1839 if (x.ndim == 1 and y.ndim == 1) and (x.shape != u.shape):
1840 x, y = np.meshgrid(x, y)
1841 u, v = self.projection.transform_vectors(t, x, y, u, v)
AttributeError: 'int' object has no attribute 'ndim'
A workaround right now is to just plot the same arrow twice on top of itself, e.g.
plt.subplot(projection=ccrs.EckertIV())
plt.quiver(np.array([0,0]),np.array([0,0]),np.array([1,1]),np.array([-1,-1]),transform=ccrs.PlateCarree())
but I was wondering if I was missing something in terms of just getting this to work normally.
I'm using cartopy 0.18.0 and matplotlib 3.2.1.
Thanks in advance for any advice!
Sometimes one must adhere to the call signature strictly.
Call signature:
quiver([X, Y], U, V, [C], **kw)
X, Y: 1D or 2D array-like
If all of the numbers of X,Y,U,V are put into array form:
plt.quiver(np.array([0]),np.array([0]), \
np.array([1]),np.array([-1]), transform=ccrs.PlateCarree())
It will work.
I am trying to create a for loop which uses a defined function (B_lambda) and takes in values of wavelength and temperature to produce values of intensity. i.e. I want the loop to take the function B_lambda and to run through every value within my listed wavelength range for each temperature in the temperature list. Then I want to plot the results. I am not very good with the syntax and have tried many ways but nothing is producing what I need and I am mostly getting errors. I have no idea how to use a for loop to plot and all online sources that I have checked out have not helped me with using a defined function in a for loop. I will put my latest code that seems to have the least errors down below with the error message:
import matplotlib.pylab as plt
import numpy as np
from astropy import units as u
import scipy.constants
%matplotlib inline
#Importing constants to use.
h = scipy.constants.h
c = scipy.constants.c
k = scipy.constants.k
wavelengths= np.arange(1000,30000)*1.e-10
temperature=[3000,4000,5000,6000]
for lam in wavelengths:
for T in temperature:
B_lambda = ((2*h*c**2)/(lam**5))*((1)/(np.exp((h*c)/(lam*k*T))-1))
plt.figure()
plt.plot(wavelengths,B_lambda)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-6-73b866241c49> in <module>
17 B_lambda = ((2*h*c**2)/(lam**5))*((1)/(np.exp((h*c)/(lam*k*T))-1))
18 plt.figure()
---> 19 plt.plot(wavelengths,B_lambda)
20
21
/usr/local/lib/python3.6/dist-packages/matplotlib/pyplot.py in plot(scalex, scaley, data, *args, **kwargs)
2787 return gca().plot(
2788 *args, scalex=scalex, scaley=scaley, **({"data": data} if data
-> 2789 is not None else {}), **kwargs)
2790
2791
/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_axes.py in plot(self, scalex, scaley, data, *args, **kwargs)
1663 """
1664 kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D._alias_map)
-> 1665 lines = [*self._get_lines(*args, data=data, **kwargs)]
1666 for line in lines:
1667 self.add_line(line)
/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_base.py in __call__(self, *args, **kwargs)
223 this += args[0],
224 args = args[1:]
--> 225 yield from self._plot_args(this, kwargs)
226
227 def get_next_color(self):
/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_base.py in _plot_args(self, tup, kwargs)
389 x, y = index_of(tup[-1])
390
--> 391 x, y = self._xy_from_xy(x, y)
392
393 if self.command == 'plot':
/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_base.py in _xy_from_xy(self, x, y)
268 if x.shape[0] != y.shape[0]:
269 raise ValueError("x and y must have same first dimension, but "
--> 270 "have shapes {} and {}".format(x.shape, y.shape))
271 if x.ndim > 2 or y.ndim > 2:
272 raise ValueError("x and y can be no greater than 2-D, but have "
ValueError: x and y must have same first dimension, but have shapes (29000,) and (1,)```
First thing to note (and this is minor) is that astropy is not required to run your code. So, you can simplify the import statements.
import matplotlib.pylab as plt
import numpy as np
import scipy.constants
%matplotlib inline
#Importing constants to use.
h = scipy.constants.h
c = scipy.constants.c
k = scipy.constants.k
wavelengths= np.arange(1000,30000,100)*1.e-10 # here, I chose steps of 100, because plotting 29000 datapoints takes a while
temperature=[3000,4000,5000,6000]
Secondly, to tidy up the loop a bit, you can write a helper function, that youn call from within you loop:
def f(lam, T):
return ((2*h*c**2)/(lam**5))*((1)/(np.exp((h*c)/(lam*k*T))-1))
now you can collect the output of your function, together with the input parameters, e.g. in a list of tuples:
outputs = []
for lam in wavelengths:
for T in temperature:
outputs.append((lam, T, f(lam, T)))
Since you vary both wavelength and temperature, a 3d plot makes sense:
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(111, projection='3d')
ax.plot(*zip(*outputs))
An alternative would be to display the data as an image, using colour to indicate the function output.
I am also including an alternative method to generate the data in this one. Since the function f can take arrays as input, you can feed one temperature at a time, and with it, all the wavelengths simultaneously.
# initialise output as array with proper shape
outputs = np.zeros((len(wavelengths), len(temperature)))
for i, T in enumerate(temperature):
outputs[:,i] = f(wavelengths, T)
The output now is a large matrix, which you can visualise as an image:
fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(outputs, aspect=10e8, interpolation='none',
extent=[
np.min(temperature),
np.max(temperature),
np.max(wavelengths),
np.min(wavelengths)]
)
I am trying to create a Choropleth map showing fire incidents throughout a county in NC. I have the data in a Dataframe and last night I was able to export maps. The only problem was that the data exported was not accurate--so there was a problem with my code. I think I managed to fix that, by merging the shapefiles and data dataframes together, but now, when I run the portion that creates the map, I get AttributeError: Unknown property column Full message:
AttributeError Traceback (most recent call last)
<ipython-input-74-61a60b41abbe> in <module>()
13 # create map
14
---> 15 merged_df.plot(column=variable, cmap='Reds', linewidth=0.8, ax=ax, edgecolor='0.8');
16
17 ax.axis('off')
~\Anaconda3\lib\site-packages\pandas\plotting\_core.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)
2939 fontsize=fontsize, colormap=colormap, table=table,
2940 yerr=yerr, xerr=xerr, secondary_y=secondary_y,
-> 2941 sort_columns=sort_columns, **kwds)
2942 __call__.__doc__ = plot_frame.__doc__
2943
~\Anaconda3\lib\site-packages\pandas\plotting\_core.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)
1975 yerr=yerr, xerr=xerr,
1976 secondary_y=secondary_y, sort_columns=sort_columns,
-> 1977 **kwds)
1978
1979
~\Anaconda3\lib\site-packages\pandas\plotting\_core.py in _plot(data, x, y, subplots, ax, kind, **kwds)
1802 plot_obj = klass(data, subplots=subplots, ax=ax, kind=kind, **kwds)
1803
-> 1804 plot_obj.generate()
1805 plot_obj.draw()
1806 return plot_obj.result
~\Anaconda3\lib\site-packages\pandas\plotting\_core.py in generate(self)
258 self._compute_plot_data()
259 self._setup_subplots()
--> 260 self._make_plot()
261 self._add_table()
262 self._make_legend()
~\Anaconda3\lib\site-packages\pandas\plotting\_core.py in _make_plot(self)
983 stacking_id=stacking_id,
984 is_errorbar=is_errorbar,
--> 985 **kwds)
986 self._add_legend_handle(newlines[0], label, index=i)
987
~\Anaconda3\lib\site-packages\pandas\plotting\_core.py in _plot(cls, ax, x, y, style, column_num, stacking_id, **kwds)
999 cls._initialize_stacker(ax, stacking_id, len(y))
1000 y_values = cls._get_stacked_values(ax, stacking_id, y, kwds['label'])
-> 1001 lines = MPLPlot._plot(ax, x, y_values, style=style, **kwds)
1002 cls._update_stacker(ax, stacking_id, y)
1003 return lines
~\Anaconda3\lib\site-packages\pandas\plotting\_core.py in _plot(cls, ax, x, y, style, is_errorbar, **kwds)
613 else:
614 args = (x, y)
--> 615 return ax.plot(*args, **kwds)
616
617 def _get_index_name(self):
~\Anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, data, *args, **kwargs)
1808 "the Matplotlib list!)" % (label_namer, func.__name__),
1809 RuntimeWarning, stacklevel=2)
-> 1810 return func(ax, *args, **kwargs)
1811
1812 inner.__doc__ = _add_data_doc(inner.__doc__,
~\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in plot(self, scalex, scaley, *args, **kwargs)
1609 kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D._alias_map)
1610
-> 1611 for line in self._get_lines(*args, **kwargs):
1612 self.add_line(line)
1613 lines.append(line)
~\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in _grab_next_args(self, *args, **kwargs)
391 this += args[0],
392 args = args[1:]
--> 393 yield from self._plot_args(this, kwargs)
394
395
~\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in _plot_args(self, tup, kwargs)
381 "with non-matching shapes is deprecated.")
382 for j in range(max(ncx, ncy)):
--> 383 seg = func(x[:, j % ncx], y[:, j % ncy], kw, kwargs)
384 ret.append(seg)
385 return ret
~\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in _makeline(self, x, y, kw, kwargs)
286 default_dict = self._getdefaults(None, kw)
287 self._setdefaults(default_dict, kw)
--> 288 seg = mlines.Line2D(x, y, **kw)
289 return seg
290
~\Anaconda3\lib\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)
408 # update kwargs before updating data to give the caller a
409 # chance to init axes (and hence unit support)
--> 410 self.update(kwargs)
411 self.pickradius = pickradius
412 self.ind_offset = 0
~\Anaconda3\lib\site-packages\matplotlib\artist.py in update(self, props)
914
915 with cbook._setattr_cm(self, eventson=False):
--> 916 ret = [_update_property(self, k, v) for k, v in props.items()]
917
918 if len(ret):
~\Anaconda3\lib\site-packages\matplotlib\artist.py in <listcomp>(.0)
914
915 with cbook._setattr_cm(self, eventson=False):
--> 916 ret = [_update_property(self, k, v) for k, v in props.items()]
917
918 if len(ret):
~\Anaconda3\lib\site-packages\matplotlib\artist.py in _update_property(self, k, v)
910 func = getattr(self, 'set_' + k, None)
911 if not callable(func):
--> 912 raise AttributeError('Unknown property %s' % k)
913 return func(v)
914
AttributeError: Unknown property column
I have no idea how to fix this. I've googled and tried changing the dtype from float to int, tried different columns, but no change. I don't understand because it worked last night, but didn't work when I tried to run it today before making changes. Thank you in advance for any help. Below is the bulk of my code that contains the data frame and mapping, everything else is just getting data from csvs:
import pandas as pd
import numpy as np
#import googlemaps
import gmaps
import gmaps.datasets
import geopandas as gpd
#import matplotlib as plt
import matplotlib.pyplot as plt
import os
import plotly.plotly as py
import plotly.tools as tls
This is what the merged dataframe looks like:
OBJECTID_x int64
ZIPNUM float64
address object
address2 object
apt_room object
arrive_date_time object
cleared_date_time object
dispatch_date_time object
exposure int64
incident_number object
incident_type int64
incident_type_description object
platoon object
station float64
Longitude object
Latitude object
Year int64
Date object
Arr Time object
Seconds float64
Incident object
OBJECTID_y int64
ZIPNAME object
ZIPCODE object
NAME object
SHAPEAREA float64
SHAPELEN float64
LAST_EDITE object
geometry object
dtype: object
# set a variable that will call column to visualise on the map
variable = 'ZIPNUM'
# set the range for the choropleth
vmin, vmax = 50, 2000
# create figure and axes for Matplotlib
fig, ax = plt.subplots(1, figsize=(15, 15))
# create map
merged_df.plot(column=variable, cmap='Reds', linewidth=0.8, ax=ax, edgecolor='0.8');
ax.axis('off')
ax.set_title('Fire Incident Rate in Wake County', fontdict={'fontsize': '25', 'fontweight' : '3'})
# Create colorbar as a legend
sm = plt.cm.ScalarMappable(cmap='Reds', norm=plt.Normalize(vmin=vmin, vmax=vmax))
# empty array for the data range
sm._A = []
# add the colorbar to the figure
cbar = fig.colorbar(sm)
ax.annotate('2008-2018',
xy=(0.001, .225), xycoords='figure fraction',
horizontalalignment='left', verticalalignment='top',
fontsize=35)
fig.savefig("Fire Incident Rate in Wake County 2008-2018.png", dpi=300)
The problem is that you are trying to use column as a keyword argument. Since you want to plot the 'ZIPNUM' column of the DataFrame, which you store in a variable called variable, you can just pass it as a positional argument to plot(). If you want to plot a relationship between two variables, you can use keyword arguments merged_df.plot(x=variable1, y=variable2)
For you case, you can use
variable = 'ZIPNUM'
merged_df.plot(variable, cmap='Reds', linewidth=0.8, ax=ax, edgecolor='0.8');
EDIT (based on comments)
You should use markeredgecolor only if you use marker for plotting. edgecolor is not the correct keyword. Moreover, you are assigning a number (string) as color which is again incorrect. Below is a simple example.
df = pd.DataFrame([[1, 2], [3, 4], [5, 6], [7, 8]], columns=["A", "B"])
column='A'
df.plot(column, linewidth=0.8, color='r', marker ='o', markeredgewidth=2,
markeredgecolor='blue')
I was following the code in the new seaborn 0.9.0 release as displayed on the site and I got an error when typing in the following code. The code came from the bottom of this page https://seaborn.pydata.org/tutorial/categorical.html
import seaborn as sns
tips = sns.load_dataset("tips")
sns.catplot(x="day", y="total_bill", hue="smoker",
col="time", aspect=.6,
kind="swarm", data=tips);
This is the output from running the above code. I have tried creating a new environment and everything has been updated. I still do not know why it is not working.
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-21-c1ae50b18a54> in <module>
3 sns.catplot(x="day", y="total_bill", hue="smoker",
4 col="time", aspect=.6,
----> 5 kind="swarm", data=tips);
6 get_ipython().run_line_magic('version_information', '')
~/anaconda3/envs/python3/lib/python3.7/site-packages/seaborn/categorical.py in catplot(x, y, hue, data, row, col, col_wrap, estimator, ci, n_boot, units, order, hue_order, row_order, col_order, kind, height, aspect, orient, color, palette, legend, legend_out, sharex, sharey, margin_titles, facet_kws, **kwargs)
3753
3754 # Draw the plot onto the facets
-> 3755 g.map_dataframe(plot_func, x, y, hue, **plot_kws)
3756
3757 # Special case axis labels for a count type plot
~/anaconda3/envs/python3/lib/python3.7/site-packages/seaborn/axisgrid.py in map_dataframe(self, func, *args, **kwargs)
818
819 # Draw the plot
--> 820 self._facet_plot(func, ax, args, kwargs)
821
822 # Finalize the annotations and layout
~/anaconda3/envs/python3/lib/python3.7/site-packages/seaborn/axisgrid.py in _facet_plot(self, func, ax, plot_args, plot_kwargs)
836
837 # Draw the plot
--> 838 func(*plot_args, **plot_kwargs)
839
840 # Sort out the supporting information
~/anaconda3/envs/python3/lib/python3.7/site-packages/seaborn/categorical.py in swarmplot(x, y, hue, data, order, hue_order, dodge, orient, color, palette, size, edgecolor, linewidth, ax, **kwargs)
2989 linewidth=linewidth))
2990
-> 2991 plotter.plot(ax, kwargs)
2992 return ax
2993
~/anaconda3/envs/python3/lib/python3.7/site-packages/seaborn/categorical.py in plot(self, ax, kws)
1444 def plot(self, ax, kws):
1445 """Make the full plot."""
-> 1446 self.draw_swarmplot(ax, kws)
1447 self.add_legend_data(ax)
1448 self.annotate_axes(ax)
~/anaconda3/envs/python3/lib/python3.7/site-packages/seaborn/categorical.py in draw_swarmplot(self, ax, kws)
1404 kws.update(c=point_colors)
1405 if self.orient == "v":
-> 1406 points = ax.scatter(cat_pos, swarm_data, s=s, **kws)
1407 else:
1408 points = ax.scatter(swarm_data, cat_pos, s=s, **kws)
~/anaconda3/envs/python3/lib/python3.7/site-packages/matplotlib/__init__.py in inner(ax, data, *args, **kwargs)
1803 "the Matplotlib list!)" % (label_namer, func.__name__),
1804 RuntimeWarning, stacklevel=2)
-> 1805 return func(ax, *args, **kwargs)
1806
1807 inner.__doc__ = _add_data_doc(inner.__doc__,
~/anaconda3/envs/python3/lib/python3.7/site-packages/matplotlib/axes/_axes.py in scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, verts, edgecolors, **kwargs)
4193 isinstance(c, str) or
4194 (isinstance(c, collections.Iterable) and
-> 4195 isinstance(c[0], str))):
4196 c_array = None
4197 else:
IndexError: index 0 is out of bounds for axis 0 with size 0
This is unfortunately a bug in matplotlib 3.0.1. It's been reported here and fixed by pull/12673.
Options you have are to install either matplotlib 3.0.0 or 3.0.2.