Matplotlib Python -> Plot_dendrogram Axis object - python

I'm building a plot_dendrogram graph and I'm struggling with the axis object. I need to create a Matplotlib axis object from 0,0.5 for the x and y axis. How do I do this?
current attempt:
plt.axis([0,.5,0,.5])
and I get the following error:
'list' object has no attribute 'set_ylim'

As the documentation states, plt.axis is a convenience function, which sets the axis limits of the current axes object.
To create the axes object, I would suggest something like this:
ax = plt.subplot(111)
ax.set_xlim([0, 0.5])
ax.set_ylim([0, 0.5])
However, I'm not sure how you got the error you posted. Even if I have not created any axes and just do:
import matplotlib.pyplot as plt
plt.axis([0,.5,0,.5])
I don't get an error.

Related

How do I change the Matplotlib axis limits for a plot given by a specific library(trackpy)?

This function gives me a plot. However I want to change the default axis. It says in documentation that ax refers to:
ax : matplotlib axes object, optional.
I tried to input the axis limit as ax=([0 100 0 500]) for example but it recognizes it as a tuple or a list. How is the correct way to input it?
Thanks!
The trackpy.plot_traj functions returns a matplotlib axes object.
So, you'll want something like:
ax = trackpy.plot_traj(traj)
ax.set_xlim([0, 100])
ax.set_ylim([0, 500])

about .show() of matplotlib

I am working with matplotlib to generate some graphs but I do not know the difference between these two ways of showing an image. I already read some documentation about it but I do not understand yet.
First way:
import matplotlib.pyplot as plt
plt.figure()
plt.plot(x, y)
plt.show()
Second way:
import matplotlib.pyplot as plt
graph = plt.figure()
plt.plot(x, y)
graph.show()
I think this two ways do not do the same thing but it is not clear to me.
Could someone explain it step by step for the two ways?
Simplified, plt.show() will start an event loop and create a graphical representation for each figure that is active inside the pyplot state.
In contrast, fig.show(), where fig is a figure instance, would show only this figure. Since it would also not block, it is (only) useful in interactive sessions; else the figure would be closed directly after showing it due to the script exiting.
In the usual case you would hence prefer plt.show(). This does not prevent you from using the object-oriented interface. A recommended way of creating and showing a figure is hence,
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(x, y)
plt.show()
For two windows you can just repeat the plotting,
import matplotlib.pyplot as plt
fig1, ax1 = plt.subplots()
ax1.plot(x1, y1)
fig2, ax2 = plt.subplots()
ax2.plot(x2, y2)
plt.show()
Matplotlib has two styles of API implemented. One is object based (graph.show()) and the other is procedural (plt.show()) and looks a lot like the Matlab plotting API.
The procedural API works on the current figure and/or set of axes. You can always getting the current figure with plt.gcf() and the current axes with plt.gca().
There are occasionally some slight differences in syntax here and there. For example, if you want to set the x axis limits:
plt.xlim([0, 10])
or
ax = plt.gca()
ax.set_xlim([0, 10])
plt.figure returns an object that is assigned with graph = plt.figure() to graph . this is used when specific characteristics of this object ( the plot ) are intended to be changed, now the object can be refered to by its instance graph ( object-based plotting )
you use this i.e. if you want to access the axes of the graph or labels, subplots, ...
see https://python4mpia.github.io/plotting/advanced.html for object-based plotting
to manipulate the plot object you have to get a reference to it ( handle ) and this is done by graph = plt.figure() ( cf Object-Oriented Programming )

matplotlib get colorbar mappable from an axis

I want to add a colorbar WITHOUT what is returned by the axis on plotting things.
Sometimes I draw things to an axis inside a function, which returns nothing.
Is there a way to get the mappable for a colorbar from an axis where a plotting has been done beforehand?
I believe there is enough information about colormap and color range bound to the axis itself.
I'd like tp do something like this:
def plot_something(ax):
ax.plot( np.random.random(10), np.random.random(10), c= np.random.random(10))
fig, axs = plt.subplots(2)
plot_something(axs[0])
plot_something(axs[1])
mappable = axs[0].get_mappable() # a hypothetical method I want to have.
fig.colorbar(mappable)
plt.show()
EDIT
The answer to the possible duplicate can partly solve my problem as is given in the code snippet. However, this question is more about retrieving a general mappable object from an axis, which seems to be impossible according to Diziet Asahi.
The way you could get your mappable would depend on what plotting function your are using in your plot_something() function.
for example:
plot() returns a Line2D object. A reference to that object is
stored in the list ax.lines of the Axes object. That being said, I don't think a Line2D can be used as a mappable for colorbar()
scatter() returns a PathCollection collection object. This object is stored in the ax.collections list of the Axes object.
On the other hand, imshow() returns an AxesImage object, which is stored in ax.images
You might have to try and look in those different list until you find an appropriate object to use.
def plot_something(ax):
x = np.random.random(size=(10,))
y = np.random.random(size=(10,))
c = np.random.random(size=(10,))
ax.scatter(x,y,c=c)
fig, ax = plt.subplots()
plot_something(ax)
mappable = ax.collections[0]
fig.colorbar(mappable=mappable)

Matplotlib alternative to fill_betweenx()

I'm trying to get the functionality of fill_betweenx() without having to use the function itself, because it doesn't accept the interpolate parameter. I need the interpolate functionality that is supported by fill_between(), but for the filling to happen relative to the x axis. It sounds like the interpolate parameter will be supported for fill_betweenx() in matplotlib 2.1, but it would be great to have access to the functionality via a workaround in the meantime.
This is the line of code in question:
ax4.fill_betweenx(x,300,p, where=p>=150, interpolate=True, facecolor='White', lw=1, zorder=2)
Unfortunately this gives me AttributeError: Unknown property interpolate.
One lazy way to do it is to use the fill_between() function with inverted coordinates on a figure that you don't show (i.e. close the figure before using plt.show()), and then re-use the vertices of the PolyCollection that fill_between() returns on your actual plot. It's not perfect, but it works as a quick fix. Here an example of what I'm talking about:
from matplotlib import pyplot as plt
from matplotlib.collections import PolyCollection
import numpy as np
fig, axes = plt.subplots(nrows = 2, ncols =2, figsize=(8,8))
#the data
x = np.linspace(0,np.pi/2,3)
y = np.sin(x)
#fill_between without interpolation
ax = axes[0,0]
ax.plot(x,y,'k')
ax.fill_between(x,0.5,y,where=y>0.25)
#fill_between with interpolation, keep the PolyCollection
ax = axes[0,1]
ax.plot(x,y,'k')
poly_col = ax.fill_between(x,0.5,y,where=y>0.25,interpolate=True)
#fill_betweenx -- no interpolation possible
ax = axes[1,0]
ax.plot(y,x,'k')
ax.fill_betweenx(x,0.5,y,where=y>0.25)
#faked fill_betweenx:
ax = axes[1,1]
ax.plot(y,x,'k')
#get the vertices from the saved PolyCollection, swap x- and y-values
v=poly_col.get_paths()[0].vertices
#convert to correct format
v2=list(zip(v[:,1],v[:,0]))
#and add to axes
ax.add_collection(PolyCollection([v2]))
#voila
plt.show()
The result of the code looks like this:

Restore left ticks in matplotlib

I have a question similar to:
Python Matplotlib Y-Axis ticks on Right Side of Plot
I fixed the problem of putting y-axis ticklabels on the right side of the plot, but I would like to restore y ticks on the left side too.
I tried with:
yax.set_ticks_position('both')
but I get:
ax0.set_ticks_position('both')
AttributeError: 'AxesSubplot' object has no attribute 'set_ticks_position'
How can I solve this problem?
You are not getting the right object on which to call set_ticks_position(). Here's a simpler way with gca():
from pylab import *
figure()
plot(arange(5))
ax = gca()
ax.yaxis.tick_right()
ax.yaxis.set_ticks_position('both')
In the second code sample you use ax0, which I guess is an Axes instance, in the first code sample you use yax, which presumably the axis-child of ax0.
I think you're looking for tick_params: ax0.tick_params(axis = 'y', direction = 'in')

Categories