Matplotlib colors not working - python

Except for the default ['r', 'g', 'c'... ] values for colors, every single color in matplotlib returns some sort of error.
For example, the following code:
import matplotlib.pyplot as plt
import matplotlib as mpl
fig, ax = plt.subplots()
ax.plot([2, 7], [1, 4], 'C1')
plt.show();
produces the error
Traceback (most recent call last):
File "/Users/homerlogistics/Downloads/colors-1.py", line 5, in <module>
ax.plot([2, 7], [1, 4], 'C1')
File "/Library/Python/2.7/site-packages/matplotlib-override/matplotlib/axes/_axes.py", line 1373, in plot
for line in self._get_lines(*args, **kwargs):
File "/Library/Python/2.7/site-packages/matplotlib-override/matplotlib/axes/_base.py", line 304, in _grab_next_args
for seg in self._plot_args(remaining, kwargs):
File "/Library/Python/2.7/site-packages/matplotlib-override/matplotlib/axes/_base.py", line 263, in _plot_args
linestyle, marker, color = _process_plot_format(tup[-1])
File "/Library/Python/2.7/site-packages/matplotlib-override/matplotlib/axes/_base.py", line 115, in _process_plot_format
'Unrecognized character %c in format string' % c)
ValueError: Unrecognized character C in format string

Related

Pandas plot error : Missing category information for StrCategoryConverter; this might be caused by unintendedly mixing categorical and numeric data

I was trying to plot a line plot using pandas plot method, the same data with exactly same method runs fine if I use matplotlib methods, however if I use df.plot then annotate gives me error ValueError: Missing category information for StrCategoryConverter; this might be caused by unintendedly mixing categorical and numeric data
Say I have a dataframe,
data = {'Unit': {0: 'Admin ', 1: 'C-Level', 2: 'Engineering', 3: 'IT', 4: 'Manufacturing', 5: 'Sales'}, 'Mean': {0: 4.642857142857143, 1: 4.83, 2: 4.048, 3: 4.237317073170732, 4: 4.184319526627219, 5: 3.9904545454545453}}
result=pd.DataFrame(data)
When using matplotlib
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(18,9))
ax.plot(results['Unit'],results['Mean'])
for i, val in enumerate(zip(results['Unit'],results['Mean'])):
label = str(results.loc[i, 'Mean'])
ax.annotate(label, val, ha='center')
plt.show()
The above code works perfectly fine.
Using pandas plot function(which gives me error)
results.plot(x = 'Unit', y = 'Mean', marker = 'o', figsize=(8,5))
ax = plt.gca()
for i, val in enumerate(zip(results['Unit'],results['Mean'])):
label = str(results.loc[i, 'Mean'])
ax.annotate(label, val, ha='center')
plt.show()
which gives me error :
Traceback (most recent call last):
File "C:\Users\hpoddar\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\axis.py", line 1506, in convert_units
ret = self.converter.convert(x, self.units, self)
File "C:\Users\hpoddar\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\category.py", line 49, in convert
raise ValueError(
ValueError: Missing category information for StrCategoryConverter; this might be caused by unintendedly mixing categorical and numeric data
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\hpoddar\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\backends\backend_qt.py", line 477, in _draw_idle
self.draw()
File "C:\Users\hpoddar\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\backends\backend_agg.py", line 436, in draw
self.figure.draw(self.renderer)
File "C:\Users\hpoddar\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\artist.py", line 73, in draw_wrapper
result = draw(artist, renderer, *args, **kwargs)
File "C:\Users\hpoddar\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\artist.py", line 50, in draw_wrapper
return draw(artist, renderer)
File "C:\Users\hpoddar\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\figure.py", line 2837, in draw
mimage._draw_list_compositing_images(
File "C:\Users\hpoddar\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\image.py", line 132, in _draw_list_compositing_images
a.draw(renderer)
File "C:\Users\hpoddar\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\artist.py", line 50, in draw_wrapper
return draw(artist, renderer)
File "C:\Users\hpoddar\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\axes\_base.py", line 3091, in draw
mimage._draw_list_compositing_images(
File "C:\Users\hpoddar\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\image.py", line 132, in _draw_list_compositing_images
a.draw(renderer)
File "C:\Users\hpoddar\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\artist.py", line 50, in draw_wrapper
return draw(artist, renderer)
File "C:\Users\hpoddar\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\text.py", line 1969, in draw
if not self.get_visible() or not self._check_xy(renderer):
File "C:\Users\hpoddar\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\text.py", line 1559, in _check_xy
xy_pixel = self._get_position_xy(renderer)
File "C:\Users\hpoddar\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\text.py", line 1552, in _get_position_xy
return self._get_xy(renderer, x, y, self.xycoords)
File "C:\Users\hpoddar\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\text.py", line 1419, in _get_xy
x = float(self.convert_xunits(x))
File "C:\Users\hpoddar\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\artist.py", line 252, in convert_xunits
return ax.xaxis.convert_units(x)
File "C:\Users\hpoddar\AppData\Local\Programs\Python\Python310\lib\site-packages\matplotlib\axis.py", line 1508, in convert_units
raise munits.ConversionError('Failed to convert value(s) to axis '
matplotlib.units.ConversionError: Failed to convert value(s) to axis units: 'Admin '
Expected output :
Annotated graph
Why am I getting error in case of pandas plot, and how can I resolve the same
matplotlib.axes.Axes.annotate() takes parameter xy as below:
xy(float, float)
The point (x, y) to annotate. The coordinate system is determined by xycoords.
Therefore to fix the issue you could create a tuple that has (i, val[1]) rather than pass val which would contain string type.
ax = results.plot(x = 'Unit', y = 'Mean', marker = 'o', figsize=(8,5))
for i, val in enumerate(zip(results['Unit'],results['Mean'])):
label = str(results.loc[i, 'Mean'])
ax.annotate(text=label, xy=(i, val[1]), ha='center')
Another option is to use matplotlib.axes.Axes.text():
ax = results.plot(x = 'Unit', y = 'Mean', marker = 'o', figsize=(8,5))
for i, val in enumerate(zip(results['Unit'],results['Mean'])):
label = str(results.loc[i, 'Mean'])
ax.text(x=i, y=val[1], s=label, ha='center')
As you noted, when we call annotate() after matplotlib.axes.Axes.plot there is no ConversionError. But if we call annotate() after pandas.DataFrame.plot there is a ConversionError.
My best guess is that after using matplotlib to plot there will be no conversion on annotate. But with a pandas plot a conversion will be attempted. This could be due to the representation of the x-ticks being different for both cases.
To demonstrate, if we try the following code the same error will be thrown:
fig, ax = plt.subplots(figsize=(18,9))
# Call annotate without plotting! Throws ConversionError
# ax.plot(results['Unit'],results['Mean'])
for i, val in enumerate(zip(results['Unit'],results['Mean'])):
label = str(results.loc[i, 'Mean'])
ax.annotate(label, val, ha='center')
Whereas if we do the following, no error will be thrown:
fig, ax = plt.subplots(figsize=(18,9))
# Call annotate without plotting! No error
# ax.plot(results['Unit'],results['Mean'])
for i, val in enumerate(zip(results['Unit'],results['Mean'])):
label = str(results.loc[i, 'Mean'])
ax.annotate(text=label, xy=(i, val[1]), ha='center')

How to fix error running local Otsu threshold example?

I am very new to Python. I am trying to run this script:
https://scikit-image.org/docs/0.12.x/auto_examples/segmentation/plot_local_otsu.html
But, I'm getting this error:
Traceback (most recent call last):
File "/Users/janine/Downloads/plot_local_otsu.py", line 37, in <module>
fig, ax = plt.subplots(2, 2, figsize=(8, 5), sharex=True, sharey=True,
File "/usr/local/lib/python3.9/site-packages/matplotlib/_api/deprecation.py", line 471, in wrapper
return func(*args, **kwargs)
File "/usr/local/lib/python3.9/site-packages/matplotlib/pyplot.py", line 1440, in subplots
axs = fig.subplots(nrows=nrows, ncols=ncols, sharex=sharex, sharey=sharey,
File "/usr/local/lib/python3.9/site-packages/matplotlib/_api/deprecation.py", line 471, in wrapper
return func(*args, **kwargs)
File "/usr/local/lib/python3.9/site-packages/matplotlib/figure.py", line 908, in subplots
axs = gs.subplots(sharex=sharex, sharey=sharey, squeeze=squeeze,
File "/usr/local/lib/python3.9/site-packages/matplotlib/gridspec.py", line 307, in subplots
axarr[row, col] = figure.add_subplot(
File "/usr/local/lib/python3.9/site-packages/matplotlib/figure.py", line 781, in add_subplot
ax = subplot_class_factory(projection_class)(self, *args, **pkw)
File "/usr/local/lib/python3.9/site-packages/matplotlib/axes/_subplots.py", line 36, in __init__
self._axes_class.__init__(self, fig, [0, 0, 1, 1], **kwargs)
File "/usr/local/lib/python3.9/site-packages/matplotlib/_api/deprecation.py", line 471, in wrapper
return func(*args, **kwargs)
File "/usr/local/lib/python3.9/site-packages/matplotlib/axes/_base.py", line 648, in __init__
self.update(kwargs)
File "/usr/local/lib/python3.9/site-packages/matplotlib/artist.py", line 1064, in update
ret.append(func(v))
File "/usr/local/lib/python3.9/site-packages/matplotlib/axes/_base.py", line 1531, in set_adjustable
_api.check_in_list(["box", "datalim"], adjustable=adjustable)
File "/usr/local/lib/python3.9/site-packages/matplotlib/_api/__init__.py", line 126, in check_in_list
raise ValueError(
ValueError: 'box-forced' is not a valid value for adjustable; supported values are 'box', 'datalim'
I have installed scikit-image exactly as recommended here:
https://scikit-image.org/docs/stable/install.html.
I am on macOS Mojave.
As you can see from the link, the example is from the outdated 0.12.x version(s) of skimage, whereas 0.18.0 is current stable version. And, as the error message indicates, the error comes from this line:
fig, ax = plt.subplots(2, 2, figsize=(8, 5), sharex=True, sharey=True,
subplot_kw={'adjustable': 'box-forced'})
Obviously, the handling of the adjustable member has changed in matplotlib.pyplot over the years. By simply removing the subplot_kw parameter at all, for example, the code runs perfectly fine:
fig, ax = plt.subplots(2, 2, figsize=(8, 5), sharex=True, sharey=True)
In fact, that's also, what the updated example from the skimage documentation looks like (second example there). Notice: You'll have to add two import statements on your own, since the given code there in incomplete.

Cannot get Proper Labels on PyPlot HeatMap from a Pandas Dataframe

Getting an error message when I try to render a heat map using this code below. This is just a way of testing this, I have much more involved application of to a large dataset about used cars...but I cannot even get past this issue with two pieces of data.
import pandas as pd
import matplotlib as plt
from matplotlib import pyplot
import numpy as np
# initialize list of lists
#Putting in numbers for the "Name" data ends up working
#data = [[3, 10], [3, 15], [6,50]]
#initializing like this with actual strings for names gives the error
data = [["James", 10], ["Mary", 15], ["Emily", 14]]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Name', 'Age'])
# print dataframe.
print(df)
plt.pyplot.pcolor(df, cmap='RdBu')
plt.pyplot.colorbar()
plt.pyplot.ylabel("Age")
plt.pyplot.xlabel("Name")
plt.pyplot.show()
The errors are as follows:
Traceback (most recent call last):
File "/home/j/dataexploratory.py", line 22, in <module>
plt.pyplot.colorbar()
File "/home/j/anaconda2/lib/python2.7/site-packages/matplotlib/pyplot.py", line 2320, in colorbar
ret = gcf().colorbar(mappable, cax = cax, ax=ax, **kw)
File "/home/j/anaconda2/lib/python2.7/site-packages/matplotlib/figure.py", line 2098, in colorbar
cb = cbar.colorbar_factory(cax, mappable, **cb_kw)
File "/home/j/anaconda2/lib/python2.7/site-packages/matplotlib/colorbar.py", line 1399, in colorbar_factory
cb = Colorbar(cax, mappable, **kwargs)
File "/home/j/anaconda2/lib/python2.7/site-packages/matplotlib/colorbar.py", line 945, in __init__
ColorbarBase.__init__(self, ax, **kw)
File "/home/j/anaconda2/lib/python2.7/site-packages/matplotlib/colorbar.py", line 327, in __init__
self.draw_all()
File "/home/j/anaconda2/lib/python2.7/site-packages/matplotlib/colorbar.py", line 349, in draw_all
self._process_values()
File "/home/j/anaconda2/lib/python2.7/site-packages/matplotlib/colorbar.py", line 703, in _process_values
expander=0.1)
File "/home/j/anaconda2/lib/python2.7/site-packages/matplotlib/transforms.py", line 2930, in nonsingular
if (not np.isfinite(vmin)) or (not np.isfinite(vmax)):
TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
Convert 'Name' to categorical dtype.

Memory error in pyplot hist

I have a list size of 1247746130. I want to get a histogram for this list:
bins = np.linspace(-100, 1, 100)
plt.hist(refList, bins, alpha=0.5, label='reference')
plt.legend(loc='upper right')
plt.savefig('reference.png')
but I get an error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 3081, in hist
stacked=stacked, data=data, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/__init__.py", line 1898, in inner
return func(ax, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/axes/_axes.py", line 6146, in hist
x = _normalize_input(x, 'x')
File "/usr/local/lib/python2.7/dist-packages/matplotlib/axes/_axes.py", line 6083, in _normalize_input
inp = np.asarray(inp)
File "/usr/local/lib/python2.7/dist-packages/numpy/core/numeric.py", line 531, in asarray
return array(a, dtype, copy=False, order=order)
MemoryError
I have 8GB RAM. Is it somehow possible to get a histogram for my data?
Thanks in advance!
I've had problems with plt.hist in the past so now use numpy.histogram. (although I think plt.hist does actually use numpy.histogram behind the scenes). An example is shown below:
import numpy as np
import matplotlib.pyplot as plt
bins = np.linspace(-100, 1, 100)
heights, edges = np.histogram(data, bins)
edges = edges[:-1]+(edges[1]-edges[0])
fig, ax = plt.subplots()
ax.plot(edges, heights)
plt.show()

Python: wrong debugging

I'm implementing some codes using PyCharm Community Edition 2016.1.4 as environment.
I have the following simple code:
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.cluster import KMeans
from sklearn import datasets
np.random.seed(5)
centers = [[1, 1], [-1, -1], [1, -1]]
iris = datasets.load_iris()
X = iris.data
y = iris.target
estimators = {'k_means_iris_3': KMeans(n_clusters=3),
'k_means_iris_8': KMeans(n_clusters=8),
'k_means_iris_bad_init': KMeans(n_clusters=3, n_init=1,
init='random')}
fignum = 1
name = 'k_means_iris_3'
est = KMeans(n_clusters=3)
fig = plt.figure(fignum, figsize=(4, 3))
plt.clf()
ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134)
est.fit(X)
labels = est.labels_
ax.scatter(X[:, 3], X[:, 0], X[:, 2], c=labels.astype(np.float))
ax.w_xaxis.set_ticklabels([])
ax.w_yaxis.set_ticklabels([])
ax.w_zaxis.set_ticklabels([])
ax.set_xlabel('Petal width')
ax.set_ylabel('Sepal length')
ax.set_zlabel('Petal length')
fignum = fignum + 1
plt.show()
If I simply run it I correctly obtain the proper image:
At the contrary, if I go in debug mode, when I arrive at the line:
fig = plt.figure(fignum, figsize=(4, 3))
I get this error:
Traceback (most recent call last):
File "C:\Program Files\Anaconda\lib\site-packages\IPython\core\interactiveshell.py", line 2885, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-1-36b230119a6b>", line 1, in <module>
fig = plt.figure(fignum, figsize=(4, 3))
File "C:\Program Files\Anaconda\lib\site-packages\matplotlib\pyplot.py", line 535, in figure
**kwargs)
File "C:\Program Files\Anaconda\lib\site-packages\matplotlib\backends\backend_qt5agg.py", line 44, in new_figure_manager
return new_figure_manager_given_figure(num, thisFig)
File "C:\Program Files\Anaconda\lib\site-packages\matplotlib\backends\backend_qt5agg.py", line 51, in new_figure_manager_given_figure
canvas = FigureCanvasQTAgg(figure)
File "C:\Program Files\Anaconda\lib\site-packages\matplotlib\backends\backend_qt5agg.py", line 223, in __init__
super(FigureCanvasQTAgg, self).__init__(figure=figure)
File "C:\Program Files\Anaconda\lib\site-packages\matplotlib\backends\backend_qt5agg.py", line 66, in __init__
super(FigureCanvasQTAggBase, self).__init__(figure=figure)
File "C:\Program Files\Anaconda\lib\site-packages\matplotlib\backends\backend_qt5.py", line 239, in __init__
super(FigureCanvasQT, self).__init__(figure=figure)
AttributeError: 'figure()' is not a Qt property or a signal
Can you imagine why?
The python error was kinda misleading. The real problem was the lack (for some reasons due to a double installation of Python) of a Python binding: PyQt4.
Just go here and, choose the proper installer and... just run it! You can also avoid to close-and-reopen the pyCharm (in a couple of seconds it fixes itself and no more errors).

Categories