Adding PolyCOllection of Violinplot into add_collection3d - python

I am trying to modify the plot shown in this answer, but replacing the fill_between with violin plots at each tick.
A naive implementation made me try following,
import matplotlib.pylab as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
x = np.linspace(1,5,100)
y1 = np.ones(x.size)
y2 = np.ones(x.size)*2
y3 = np.ones(x.size)*3
z = np.sin(x/2)
plt.figure()
ax = plt.subplot(projection='3d')
ax.plot(x, y1, z, color='r')
ax.plot(x, y2, z, color='g')
ax.plot(x, y3, z, color='b')
handle = plt.violinplot(x)
ax.add_collection3d(handle, zs=1, zdir='y')
The error that pops up is: AttributeError: 'PolyCollection' object has no attribute 'do_3d_projection'.
The error origin can be traced by the following log:
runcell(7, 'Figure.py')
Traceback (most recent call last):
File "Figure.py", line 163, in <module>
ax.add_collection3d(handle, zs=1, zdir='y')
File "C:\Users\sarth\.conda\envs\master\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py", line 2252, in add_collection3d
super().add_collection(col)
File "C:\Users\sarth\.conda\envs\master\lib\site-packages\matplotlib\axes\_base.py", line 1921, in add_collection
label = collection.get_label()
AttributeError: 'dict' object has no attribute 'get_label'
Traceback (most recent call last):
File "C:\Users\sarth\AppData\Roaming\Python\Python36\site-packages\IPython\core\formatters.py", line 341, in __call__
return printer(obj)
File "C:\Users\sarth\AppData\Roaming\Python\Python36\site-packages\IPython\core\pylabtools.py", line 248, in <lambda>
png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
File "C:\Users\sarth\AppData\Roaming\Python\Python36\site-packages\IPython\core\pylabtools.py", line 132, in print_figure
fig.canvas.print_figure(bytes_io, **kw)
File "C:\Users\sarth\.conda\envs\master\lib\site-packages\matplotlib\backend_bases.py", line 2193, in print_figure
self.figure.draw(renderer)
File "C:\Users\sarth\.conda\envs\master\lib\site-packages\matplotlib\artist.py", line 41, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "C:\Users\sarth\.conda\envs\master\lib\site-packages\matplotlib\figure.py", line 1864, in draw
renderer, self, artists, self.suppressComposite)
File "C:\Users\sarth\.conda\envs\master\lib\site-packages\matplotlib\image.py", line 131, in _draw_list_compositing_images
a.draw(renderer)
File "C:\Users\sarth\.conda\envs\master\lib\site-packages\matplotlib\artist.py", line 41, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "C:\Users\sarth\.conda\envs\master\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py", line 447, in draw
reverse=True)):
File "C:\Users\sarth\.conda\envs\master\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py", line 446, in <lambda>
key=lambda col: col.do_3d_projection(renderer),
AttributeError: 'PolyCollection' object has no attribute 'do_3d_projection'
<Figure size 432x288 with 1 Axes>
Also tried using individual body objects using plt.violinplot(x)['objects'][i] but the same error is returned.

Related

Invalid RGBA color "ro" in matplotlib while using the plot() function

I've been trying to use the Figure.figure.plot() function from matplotlib
figplot = fig.add_subplot(111)
print(lines[2].get_xdata()[0])
print(lines[2].get_ydata()[0])
figplot.plot(lines[2].get_xdata()[0], lines[2].get_ydata()[0], c='ro')
but upon trying to execute this, I'm getting the following error message:
Traceback (most recent call last):
File "/usr/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
File "/usr/local/lib/python3.7/dist-packages/matplotlib/backends/_backend_tk.py", line 259, in resize
self.draw()
File "/usr/local/lib/python3.7/dist-packages/matplotlib/backends/backend_tkagg.py", line 9, in draw
super(FigureCanvasTkAgg, self).draw()
File "/usr/local/lib/python3.7/dist-packages/matplotlib/backends/backend_agg.py", line 388, in draw
self.figure.draw(self.renderer)
File "/usr/local/lib/python3.7/dist-packages/matplotlib/artist.py", line 38, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/matplotlib/figure.py", line 1709, in draw
renderer, self, artists, self.suppressComposite)
File "/usr/local/lib/python3.7/dist-packages/matplotlib/image.py", line 135, in _draw_list_compositing_images
a.draw(renderer)
File "/usr/local/lib/python3.7/dist-packages/matplotlib/artist.py", line 38, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/matplotlib/axes/_base.py", line 2647, in draw
mimage._draw_list_compositing_images(renderer, self, artists)
File "/usr/local/lib/python3.7/dist-packages/matplotlib/image.py", line 135, in _draw_list_compositing_images
a.draw(renderer)
File "/usr/local/lib/python3.7/dist-packages/matplotlib/artist.py", line 38, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/matplotlib/lines.py", line 783, in draw
lc_rgba = mcolors.to_rgba(self._color, self._alpha)
File "/usr/local/lib/python3.7/dist-packages/matplotlib/colors.py", line 177, in to_rgba
rgba = _to_rgba_no_colorcycle(c, alpha)
File "/usr/local/lib/python3.7/dist-packages/matplotlib/colors.py", line 233, in _to_rgba_no_colorcycle
raise ValueError("Invalid RGBA argument: {!r}".format(orig_c))
ValueError: Invalid RGBA argument: 'ro'
I've noticed that for scatter plots, the colors have to be an array, but this isn't a scatter plot.
the values of lines[2].get_xdata()[0] and lines[2].get_ydata()[0] is as follows:
0.5766199490353112
1648.0609161647387
Is there any way to find out what's going wrong? I'm using tkinter along with matplotlib
ro is color-marker code. You should remove c=:
figplot.plot(lines[2].get_xdata()[0], lines[2].get_ydata()[0], 'ro')
Or maybe specify color without the marker o:
figplot.plot(lines[2].get_xdata()[0], lines[2].get_ydata()[0], c='r')

Issue with tight_layout in matplotlib rendering

I have the following code:
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.ticker import AutoMinorLocator
import matplotlib.ticker as ticker
import pylab as pl
import numpy as np
matplotlib.rc('font',**{'family':'sans-serif','sans-serif':['Helvetica'], 'weight':'bold'})
from matplotlib.font_manager import fontManager, FontProperties
matplotlib.rcParams['mathtext.fontset'] = 'custom'
matplotlib.rcParams['mathtext.rm'] = 'Helvetica'
matplotlib.rcParams['mathtext.it'] = 'Helvetica:italic'
matplotlib.rcParams['mathtext.bf'] = 'Helvetica:bold'
font= FontProperties(weight='bold',size=18)
data = np.genfromtxt('data', names=True, dtype=None, usecols=("x", "y1", "y2", "y3"))
x = data['x']
n = data['y1']
j = data['y2']
v = data['y3']
minorLocator = AutoMinorLocator(2)
def format():
for axis in ['top','bottom','left','right']:
ax.spines[axis].set_linewidth(3)
for tick in ax.yaxis.get_ticklabels():
tick.set_fontsize(22)
tick.set_weight('bold')
for tick in ax.xaxis.get_ticklabels():
tick.set_fontsize(22)
tick.set_weight('bold')
ax.set_ylabel(r'$\mathrm{ \Delta{}E_{solv}^{imp}}$',fontsize=26,fontweight='bold')
ax.tick_params(axis='x', which='both', direction='in', length=10, width=3, pad=8, top='off')
ax.tick_params(axis='y', which='major', direction='in', length=10, width=3, pad=8, right='off')
ax.tick_params(axis='y', which='minor', direction='in', length=6, width=2, right='off')
fig = plt.figure(figsize=(9.6,12), dpi=300, linewidth=3.0)
ax = fig.add_subplot(211)
r=np.arange(1,25,1.5)
p1 = ax.bar(r,v,width=0.9,color='white',edgecolor='black', lw=1.0, align='center')
p2 = ax.bar(r,j,width=0.6,color='red',edgecolor='black', lw=1.0, align='center')
p3 = ax.bar(r,n,width=0.3,color='black',edgecolor='black', lw=1.0, align='center')
ax.set_xticks(r)
ax.set_xticklabels(x,rotation=45)
format()
plt.axhline(y=0,linewidth=1,color='black')
plt.axis([0.0,24.5,-0.36,0.15])
ax.yaxis.set_minor_locator(minorLocator)
pl.rc('axes',linewidth=3)
ax.xaxis.grid(True,which='major',color='gray', linestyle='--',linewidth=0.5)
ax.set_axisbelow(True)
data = np.genfromtxt('data-2', names=True, dtype=None, usecols=("x", "y1"))
x = data['x']
n = data['y1']
ax = fig.add_subplot(212)
r=np.arange(1,31,1.5)
p1 = ax.bar(r,v,width=0.9,color='red',edgecolor='black', lw=1.0, align='center')
ax.set_xticks(r)
ax.set_xticklabels(x,rotation=90)
format()
plt.axhline(y=0,linewidth=1,color='black')
plt.axis([0.0,30.5,-0.48,0.40])
for label in ax.xaxis.get_ticklabels():
label.set_horizontalalignment('center')
ax.yaxis.set_minor_locator(minorLocator)
pl.rc('axes',linewidth=3)
ax.xaxis.grid(True,which='major',color='gray',linestyle='--',linewidth=0.5)
ax.set_axisbelow(True)
fig.set_tight_layout(True) #tried plt.tight_layout() also. didn't work
plt.savefig('image.png',dpi=300,format='png', orientation='landscape')
I am not able to save plt.show() the graph. I get the following error. I still keep getting the same error even if I delete the fig.set_tight_layout(True) line. The reason for posting this whole code is that I am not able to reproduce the same error if I run part of the code.
Thank you for the help.
Traceback (most recent call last):
File "image.py", line 83, in <module>
plt.savefig('image.png',dpi=300,format='png', orientation='landscape')
File "/usr/local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 576, in savefig
res = fig.savefig(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/matplotlib/figure.py", line 1470, in savefig
self.canvas.print_figure(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/matplotlib/backend_bases.py", line 2192, in print_figure
**kwargs)
File "/usr/local/lib/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 513, in print_png
FigureCanvasAgg.draw(self)
File "/usr/local/lib/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 461, in draw
self.figure.draw(self.renderer)
File "/usr/local/lib/python2.7/site-packages/matplotlib/artist.py", line 59, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/matplotlib/figure.py", line 1079, in draw
func(*args)
File "/usr/local/lib/python2.7/site-packages/matplotlib/artist.py", line 59, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/matplotlib/axes/_base.py", line 2092, in draw
a.draw(renderer)
File "/usr/local/lib/python2.7/site-packages/matplotlib/artist.py", line 59, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/matplotlib/axis.py", line 1105, in draw
renderer)
File "/usr/local/lib/python2.7/site-packages/matplotlib/axis.py", line 1054, in _get_tick_bboxes
extent = tick.label1.get_window_extent(renderer)
File "/usr/local/lib/python2.7/site-packages/matplotlib/text.py", line 741, in get_window_extent
bbox, info, descent = self._get_layout(self._renderer)
File "/usr/local/lib/python2.7/site-packages/matplotlib/text.py", line 320, in _get_layout
ismath=ismath)
File "/usr/local/lib/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 220, in get_text_width_height_descent
self.mathtext_parser.parse(s, self.dpi, prop)
File "/usr/local/lib/python2.7/site-packages/matplotlib/mathtext.py", line 3005, in parse
box = self._parser.parse(s, font_output, fontsize, dpi)
File "/usr/local/lib/python2.7/site-packages/matplotlib/mathtext.py", line 2339, in parse
six.text_type(err)]))
ValueError:
_
^
Expected "\" (at char 1), (line:1, col:2)
It was actually some math formatting related issue although not in ylabel. I do not know why but reentering all the list elements (containing several $A_a$) again worked.

loglog plot with matplotlib in pyqt - axes disappear

I am trying to use matplotlib plotting library inside PyQt4 to plot loglog plot. I have added two lines of code in the class:
class MyStaticMplCanvas(MyMplCanvas):
"""Simple canvas with a sine plot."""
def compute_initial_figure(self):
t = arange(0.0, 3.0, 0.01)
s = abs((t * 1E+1) * sin(2 * pi * t) + 1E1)
self.axes.plot(t, s)
self.axes.set_yscale('log') #added code
self.axes.set_xscale('log') #added code
but then axes disappeared and got an error below. I would like to ask you how can I use matplotlib library inside PyQt4 to plot loglot plot. As seen in the figure below. Python 2.7.5, matplotlib 1.3.0, PyQt 4.10.4
Traceback (most recent call last):
File "C:\Python27\Lib\site-packages\matplotlib\backends\backend_qt4.py", line 299, in resizeEvent
self.draw()
File "C:\Python27\Lib\site-packages\matplotlib\backends\backend_qt4agg.py", line 148, in draw
FigureCanvasAgg.draw(self)
File "C:\Python27\Lib\site-packages\matplotlib\backends\backend_agg.py", line 451, in draw
self.figure.draw(self.renderer)
File "C:\Python27\Lib\site-packages\matplotlib\artist.py", line 54, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Python27\Lib\site-packages\matplotlib\figure.py", line 1034, in draw
func(*args)
File "C:\Python27\Lib\site-packages\matplotlib\artist.py", line 54, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Python27\Lib\site-packages\matplotlib\axes.py", line 2086, in draw
a.draw(renderer)
File "C:\Python27\Lib\site-packages\matplotlib\artist.py", line 54, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Python27\Lib\site-packages\matplotlib\axis.py", line 1093, in draw
renderer)
File "C:\Python27\Lib\site-packages\matplotlib\axis.py", line 1042, in _get_tick_bboxes
extent = tick.label1.get_window_extent(renderer)
File "C:\Python27\Lib\site-packages\matplotlib\text.py", line 754, in get_window_extent
bbox, info, descent = self._get_layout(self._renderer)
File "C:\Python27\Lib\site-packages\matplotlib\text.py", line 329, in _get_layout
ismath=ismath)
File "C:\Python27\Lib\site-packages\matplotlib\backends\backend_agg.py", line 210, in get_text_width_height_descent
self.mathtext_parser.parse(s, self.dpi, prop)
File "C:\Python27\Lib\site-packages\matplotlib\mathtext.py", line 3009, in parse
self.__class__._parser = Parser()
File "C:\Python27\Lib\site-packages\matplotlib\mathtext.py", line 2193, in __init__
- ((lbrace + float_literal + rbrace)
TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'
This is probably because your x-range includes 0. True log scales can't reach 0. If you want to include 0, you'll need to use 'semilog' instead.
Judging from the error message you're getting, I'd bet you're using a fairly old release of matplotlib? For what it's worth, in newer versions, including 0 will cause the scale to be automatically changed to semilog instead of log.
Either way, try specifying a semilog scale, and see if that helps. E.g.
self.axes.set(xscale='semilog', yscale='semilog')

matplotlib contourf() raises exception "ValueError: array is too big."

I'm trying to plot a data set (777 x 576) with 3D contours. This appears to be working fine until I try to place the contour under the 3d plot.
from mpl_toolkits.mplot3d import axes3d
from matplotlib import cm, pyplot
import numpy
X,Y = numpy.mgrid[:len(data), :len(data[0])]
fig = pyplot.figure('''figsize=(20, 10), dpi=800''')
ax = fig.gca(projection='3d')
ax.plot_surface(X,
Y,
data,
rstride=100,
cstride=100,
alpha=0.3,
linewidths=(.5,),
antialiased=True,
)
# cset = ax.contourf(X, Y, data, zdir='z', offset=130, cmap=cm.coolwarm)
ax.set_xlim(800, 0)
ax.set_ylim(0, 600)
ax.set_zlim(130, 170)
plt.show()
That is to say that uncommenting the ax.contourf(...) line causes the following exception:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1470, in __call__
return self.func(*args)
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 276, in resize
self.show()
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 348, in draw
FigureCanvasAgg.draw(self)
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_agg.py", line 451, in draw
self.figure.draw(self.renderer)
File "C:\Python27\lib\site-packages\matplotlib\artist.py", line 55, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\figure.py", line 1034, in draw
func(*args)
File "C:\Python27\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py", line 248, in draw
for col in self.collections]
File "C:\Python27\lib\site-packages\mpl_toolkits\mplot3d\art3d.py", line 456, in do_3d_projection
cedge = cedge.repeat(len(xyzlist), axis=0)
ValueError: array is too big.
In case this means anything:
len(cedge) == 35656
len(xyzlist) == 8914
35656 * 8914 = 317837584
Is there something I need to set to accommodate my data set?

python: AttributeError: 'ZAxis' object has no attribute '_set_scale'

I recently updated to OS X Maverics and as one of the results it broke my python matplotlib 3D plotting. For example when I run this:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
I get:
Traceback (most recent call last):
File "/Users/nacho/Documents/Proyecto/codigo/RLS/run_rls.py", line 89, in <module>
n_plot([bunch.ff_weighted_estimation_error for bunch in rls.rls_bunchs], 'Peso')
File "/Users/nacho/Documents/Proyecto/codigo/RLS/run_rls.py", line 43, in n_plot
ax = fig.gca(projection='3d')
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/figure.py", line 1066, in gca
return self.add_subplot(111, **kwargs)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/figure.py", line 789, in add_subplot
a = subplot_class_factory(projection_class)(self, *args, **kwargs)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/axes.py", line 8457, in __init__
self._axes_class.__init__(self, fig, self.figbox, **kwargs)
File "/Library/Python/2.7/site-packages/mpl_toolkits/mplot3d/axes3d.py", line 91, in __init__
*args, **kwargs)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/axes.py", line 463, in __init__
self.cla()
File "/Library/Python/2.7/site-packages/mpl_toolkits/mplot3d/axes3d.py", line 1040, in cla
self.zaxis._set_scale('linear')
AttributeError: 'ZAxis' object has no attribute '_set_scale'
I'm running Python 2.7.5, and matplotlib 1.3.1.

Categories