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.
Related
I want to plot a bar graph for labels in y axis and on x axis the number of datapoints each label has. But I am getting the following error, can anyone please help me with the correct code?
I am writing this code to visualize the number of datapoints divided among labels (0,1,2,3,4...9).
%matplotlib inline
import matplotlib.pyplot as plt
pip install watermark
%load_ext watermark
%watermark -u -v -d -p matplotlib,numpy
%matplotlib inline
import matplotlib.pyplot as plt
# input data
mean_values = [0, 1500, 0, 0, 6000, 1000, 1500, 2000, 1200] #y labels
bar_labels = ['0', '1', '2', '3', '4', '5','6', '7', '8','9'] #x_labels
# plot bars
x_pos = list(range(len(bar_labels)))
rects = plt.bar(x_pos, mean_values, align='center', alpha=0.5)
# label bars
def autolabel(rects):
for ii,rect in enumerate(rects):
height = rect.get_height()
plt.text(rect.get_x()+rect.get_width()/2., 1.02*height, '%s'% (mean_values[ii]),
ha='center', va='bottom')
autolabel(rects)
# set height of the y-axis
max_y = max(zip(mean_values, variance)) # returns a tuple, here: (3, 5)
plt.ylim([0, (max_y[0] + max_y[1]) * 1.1])
# set axes labels and title
plt.ylabel('variable y')
plt.xticks(x_pos, bar_labels)
plt.title('Bar plot with labels')
plt.show()
Error message:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-15-25c2776ed492> in <module>
7 # plot bars
8 x_pos = list(range(len(bar_labels)))
----> 9 rects = plt.bar(x_pos, mean_values, align='center', alpha=0.5)
10
11 # label bars
4 frames
/usr/local/lib/python3.7/dist-packages/matplotlib/pyplot.py in bar(x, height, width, bottom, align, data, **kwargs)
2407 return gca().bar(
2408 x, height, width=width, bottom=bottom, align=align,
-> 2409 **({"data": data} if data is not None else {}), **kwargs)
2410
2411
/usr/local/lib/python3.7/dist-packages/matplotlib/__init__.py in inner(ax, data, *args, **kwargs)
1563 def inner(ax, *args, data=None, **kwargs):
1564 if data is None:
-> 1565 return func(ax, *map(sanitize_sequence, args), **kwargs)
1566
1567 bound = new_sig.bind(ax, *args, **kwargs)
/usr/local/lib/python3.7/dist-packages/matplotlib/axes/_axes.py in bar(self, x, height, width, bottom, align, **kwargs)
2340 x, height, width, y, linewidth = np.broadcast_arrays(
2341 # Make args iterable too.
-> 2342 np.atleast_1d(x), height, width, y, linewidth)
2343
2344 # Now that units have been converted, set the tick locations.
<__array_function__ internals> in broadcast_arrays(*args, **kwargs)
/usr/local/lib/python3.7/dist-packages/numpy/lib/stride_tricks.py in broadcast_arrays(subok, *args)
536 args = [np.array(_m, copy=False, subok=subok) for _m in args]
537
--> 538 shape = _broadcast_shape(*args)
539
540 if all(array.shape == shape for array in args):
/usr/local/lib/python3.7/dist-packages/numpy/lib/stride_tricks.py in _broadcast_shape(*args)
418 # use the old-iterator because np.nditer does not handle size 0 arrays
419 # consistently
--> 420 b = np.broadcast(*args[:32])
421 # unfortunately, it cannot handle 32 or more arguments directly
422 for pos in range(32, len(args), 31):
ValueError: shape mismatch: objects cannot be broadcast to a single shape
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.
I'm using the following code.
%matplotlib notebook
plt.style.use('seaborn-bright')
fig,ax = plt.subplots(figsize=(8,6), facecolor='w', edgecolor='blue')
ax.spines['top'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
plt.title('Clubs of Severn Valley Petanque League - performance in years 2014-2019',color='purple',size=14.5,y=1.09)
ax.set_ylabel('Year', color='indigo',size=10)
ax.set_ylabel('Points won', color='darkblue', fontdict={'fontsize': 12, 'fontweight': 'medium'})
years=[2014,2015, 2016,2017,2018, 2019]
plt.xticks(np.arange(5), (years))
plt.margins(x=0.006,y=0.009)
ax.get_xaxis().tick_bottom()
ax.get_yaxis().tick_left()
ax.yaxis.set_major_formatter(plt.FuncFormatter('{:.0f}'.format))
ax.grid(True, 'major', 'y', ls='--', lw=.6, c='darkgray', alpha=.5)
ax.tick_params(axis='y', which='both', labelsize=10,bottom=False, top=False, labelbottom=True,
left=False, right=False, labelleft=True)
plt.legend(loc=2)
# Now I call each column( one for each team) one by one like so :
plt.plot(final.Points_Kinver.values, marker='o', label='Kinver Con Club')
plt.plot(final.Points_Nomads.values, marker='o', label='Nomads')
plt.plot(final.Points_TopPub.values, marker='o', label='Top Pub')
plt.plot(final.Points_Plough.values, marker='o', label='Plough')
plt.plot(final.Points_AlveleyRoyals.values, '-o', c='violet', label='Alveley Royals')
plt.plot(final.Points_Footloose.values, marker='o', c='yellow', label='Footloose')
plt.plot(final.Points_Gaters.values, '-o', c='orange', label="Gaters 'A'")
plt.plot(final.Points_AlveleyOaks.values, '-o',c='darkgreen', label='Alveley Oaks')
plt.show()
It works. Here is my chart .
However, I wish I could write plt.plot as one line, and this does not work.
plt.plot(final.columns.values, marker='o')
This causes an error.
TypeError Traceback (most recent call last)
<ipython-input-277-f48c020019fc> in <module>()
44 #mychart=final.plot( marker='o',ax=ax)
45
---> 46 plt.plot(final.columns.values, marker='o')
47
48 #plt.plot(final.Points_Kinver.values, marker='o', label='Kinver Con Club')
~\Anaconda3\lib\site-packages\matplotlib\pyplot.py in plot(*args, **kwargs)
3356 mplDeprecation)
3357 try:
-> 3358 ret = ax.plot(*args, **kwargs)
3359 finally:
3360 ax._hold = washold
~\Anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, *args, **kwargs)
1853 "the Matplotlib list!)" % (label_namer, func.__name__),
1854 RuntimeWarning, stacklevel=2)
-> 1855 return func(ax, *args, **kwargs)
1856
1857 inner.__doc__ = _add_data_doc(inner.__doc__,
~\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in plot(self, *args, **kwargs)
1525 kwargs = cbook.normalize_kwargs(kwargs, _alias_map)
1526
-> 1527 for line in self._get_lines(*args, **kwargs):
1528 self.add_line(line)
1529 lines.append(line)
~\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in _grab_next_args(self, *args, **kwargs)
404 this += args[0],
405 args = args[1:]
--> 406 for seg in self._plot_args(this, kwargs):
407 yield seg
408
~\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in _plot_args(self, tup, kwargs)
381 x, y = index_of(tup[-1])
382
--> 383 x, y = self._xy_from_xy(x, y)
384
385 if self.command == 'plot':
~\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in _xy_from_xy(self, x, y)
214 if self.axes.xaxis is not None and self.axes.yaxis is not None:
215 bx = self.axes.xaxis.update_units(x)
--> 216 by = self.axes.yaxis.update_units(y)
217
218 if self.command != 'plot':
~\Anaconda3\lib\site-packages\matplotlib\axis.py in update_units(self, data)
1467 neednew = self.converter != converter
1468 self.converter = converter
-> 1469 default = self.converter.default_units(data, self)
1470 if default is not None and self.units is None:
1471 self.set_units(default)
~\Anaconda3\lib\site-packages\matplotlib\category.py in default_units(data, axis)
113 # default_units->axis_info->convert
114 if axis.units is None:
--> 115 axis.set_units(UnitData(data))
116 else:
117 axis.units.update(data)
~\Anaconda3\lib\site-packages\matplotlib\category.py in __init__(self, data)
180 self._counter = itertools.count(start=0)
181 if data is not None:
--> 182 self.update(data)
183
184 def update(self, data):
~\Anaconda3\lib\site-packages\matplotlib\category.py in update(self, data)
199 for val in OrderedDict.fromkeys(data):
200 if not isinstance(val, VALID_TYPES):
--> 201 raise TypeError("{val!r} is not a string".format(val=val))
202 if val not in self._mapping:
203 self._mapping[val] = next(self._counter)
TypeError: ('Points_Kinver',) is not a string
I have also tried
ax=final.plot( marker='o')
for line, name in zip(ax.lines, final.columns):
y = line.get_ydata()[-1]
ax.annotate(name, xy=(1,y), xytext=(6,0), color=line.get_color(),
xycoords = ax.get_yaxis_transform(), textcoords="offset points",
size=8, va="center")
It works. However, it creates 2 figures.
Figure 1: the empty customized figure with all of my carefully coded formatting, more specifically, ticks and gridlines ( ax.grid...) and the chart title.
Figure 2: it contains the lines with labels, but all customized formatting and the title are lost.
Can you explain what is happening here?
My next step is labelling the end of each line instead of the legend.
so I thought I need my plt.plot code in a single line..
As you can see, I'm not very experienced in matplotlib/python. I am trying to practice by creating a visualisation for my local petanque association. thank you for your help with my little project.
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 am using seaborn to plot a very simple data set. Here is what I do:
import seaborn as sns
import pandas as pd
df = pd.read_excel('myfile.xlsx')
sns.set(style="white")
g = sns.PairGrid(df, diag_sharey=False)
g.map_lower(sns.kdeplot)
g.map_upper(sns.scatterplot)
g.map_diag(sns.kdeplot, lw=3)
I get the following error: AttributeError: 'NoneType' object has no attribute 'ndim'. Weirdly, the plot is ploted in parts (see below).
Any idea why that is the case and what I can do to solve the issue?
EDIT:
The dataframe has the following attributes:
plan_change int64
user_login float64
new_act_ratio float64
on_time int64
Unfortunately, I cannot upload the data set. However I can say, that plotting other seaborn graphs works just fine.
The total error message is the following:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-16-2dbc61abd2bd> in <module>()
3 g = sns.PairGrid(df, diag_sharey=False)
4 g.map_lower(sns.kdeplot)
----> 5 g.map_upper(sns.scatterplot)
6 g.map_diag(sns.kdeplot, lw=3)
7
/anaconda/lib/python3.5/site-packages/seaborn/axisgrid.py in map_upper(self, func, **kwargs)
1488 color = self.palette[k] if kw_color is None else kw_color
1489 func(data_k[x_var], data_k[y_var], label=label_k,
-> 1490 color=color, **kwargs)
1491
1492 self._clean_axis(ax)
/anaconda/lib/python3.5/site-packages/seaborn/relational.py in scatterplot(x, y, hue, style, size, data, palette, hue_order, hue_norm, sizes, size_order, size_norm, markers, style_order, x_bins, y_bins, units, estimator, ci, n_boot, alpha, x_jitter, y_jitter, legend, ax, **kwargs)
1333 x_bins=x_bins, y_bins=y_bins,
1334 estimator=estimator, ci=ci, n_boot=n_boot,
-> 1335 alpha=alpha, x_jitter=x_jitter, y_jitter=y_jitter, legend=legend,
1336 )
1337
/anaconda/lib/python3.5/site-packages/seaborn/relational.py in __init__(self, x, y, hue, size, style, data, palette, hue_order, hue_norm, sizes, size_order, size_norm, dashes, markers, style_order, x_bins, y_bins, units, estimator, ci, n_boot, alpha, x_jitter, y_jitter, legend)
850
851 plot_data = self.establish_variables(
--> 852 x, y, hue, size, style, units, data
853 )
854
/anaconda/lib/python3.5/site-packages/seaborn/relational.py in establish_variables(self, x, y, hue, size, style, units, data)
155 units=units
156 )
--> 157 plot_data = pd.DataFrame(plot_data)
158
159 # Option 3:
/anaconda/lib/python3.5/site-packages/pandas/core/frame.py in __init__(self, data, index, columns, dtype, copy)
264 dtype=dtype, copy=copy)
265 elif isinstance(data, dict):
--> 266 mgr = self._init_dict(data, index, columns, dtype=dtype)
267 elif isinstance(data, ma.MaskedArray):
268 import numpy.ma.mrecords as mrecords
/anaconda/lib/python3.5/site-packages/pandas/core/frame.py in _init_dict(self, data, index, columns, dtype)
400 arrays = [data[k] for k in keys]
401
--> 402 return _arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype)
403
404 def _init_ndarray(self, values, index, columns, dtype=None, copy=False):
/anaconda/lib/python3.5/site-packages/pandas/core/frame.py in _arrays_to_mgr(arrays, arr_names, index, columns, dtype)
5382
5383 # don't force copy because getting jammed in an ndarray anyway
-> 5384 arrays = _homogenize(arrays, index, dtype)
5385
5386 # from BlockManager perspective
/anaconda/lib/python3.5/site-packages/pandas/core/frame.py in _homogenize(data, index, dtype)
5693 v = lib.fast_multiget(v, oindex.values, default=NA)
5694 v = _sanitize_array(v, index, dtype=dtype, copy=False,
-> 5695 raise_cast_failure=False)
5696
5697 homogenized.append(v)
/anaconda/lib/python3.5/site-packages/pandas/core/series.py in _sanitize_array(data, index, dtype, copy, raise_cast_failure)
2917
2918 # scalar like
-> 2919 if subarr.ndim == 0:
2920 if isinstance(data, list): # pragma: no cover
2921 subarr = np.array(data, dtype=object)
AttributeError: 'NoneType' object has no attribute 'ndim'