Question:
Color matplotlib bar chart based on value Is there a way to color the bars of a barchart based on the bar's value. For example:
```
- values below -0.5: red
- values between -0.5 to 0: green
- values between 0 to 08: blue
- etc
```
I have found some basic examples of bar coloring but nothing which can cater for value ranges, such as the above examples. UPDATE: Thank you kikocorreoso for your suggestion. This works great when both axes are numbers as per your example. However in my case my original data structure is a pandas dataframe. I then use df.stack() and plot the result. This means that the dataframes rows/columns become the x axis of the plot and the dataframe cells are the Y axis (bars). I have tried masking as per your example but it doesn't seem to work when the Y axis are numbers and the X axis are names. eg:
```
col1    col2   col3   col4
 row1 1       2      3      4
 row2 5       6      7      8
 row3 9       10     11     12
 row4 13      14     15     16
```
The above dataframe needs to be plotted as a barchart with the row/column combinations forming the x-axis. Each cell value will be a bar. And ultimately, coloring the bars as per the original question. Thanks

Response:
You could use masks for your datasets. A basic example could be the following:
```
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(10)
y = np.arange(10) * 0.1

mask1 = y < 0.5
mask2 = y >= 0.5

plt.bar(x[mask1], y[mask1], color = 'red')
plt.bar(x[mask2], y[mask2], color = 'blue')
plt.show()
```
The result should be: UPDATE: As you updated your question I update the code. For your simple case, and if I understood correctly, you could do the following (ugly) hack:
```
import pandas as pd

df = pd.DataFrame({'col1':[1,2,3], 'col2':[4,5,6]},
                  index = ['row1','row2','row3'])

dfstacked = df.stack()

mask = dfstacked <= 3

colors = np.array(['b']*len(dfstacked))
colors[mask.values] = 'r'

dfstacked.plot(kind = 'bar', rot = 45, color = colors)
plt.show()
```
Or use a more OO solution. The code briefly explained: I create a mask for my red columns I create an array of colors Change the the array of colors in order to use other color for my masked values As the dfstacked dataframe has a MultiIndex the ticks are not well printed so I use the rot keyword to rotate them. If you want to automate it in order to get a nice plot you can use plt.tight_layout() before plt.show(). I hope it helps.


Question:
How to plot one line in different colors I have two list as below:
```
latt=[42.0,41.978567980875397,41.96622693388357,41.963791391892457,...,41.972407378075879]
lont=[-66.706920989908909,-66.703116557977069,-66.707351643324543,...-66.718218142021925]
```
now I want to plot this as a line, separate each 10 of those 'latt' and 'lont' records as a period and give it a unique color. what should I do?

Response:
There are several different ways to do this. The "best" approach will depend mostly on how many line segments you want to plot. If you're just going to be plotting a handful (e.g. 10) line segments, then just do something like:
```
import numpy as np
import matplotlib.pyplot as plt

def uniqueish_color():
    """There're better ways to generate unique colors, but this isn't awful."""
    return plt.cm.gist_ncar(np.random.random())

xy = (np.random.random((10, 2)) - 0.5).cumsum(axis=0)

fig, ax = plt.subplots()
for start, stop in zip(xy[:-1], xy[1:]):
    x, y = zip(start, stop)
    ax.plot(x, y, color=uniqueish_color())
plt.show()
```
If you're plotting something with a million line segments, though, this will be terribly slow to draw. In that case, use a LineCollection. E.g.
```
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

xy = (np.random.random((1000, 2)) - 0.5).cumsum(axis=0)

# Reshape things so that we have a sequence of:
# [[(x0,y0),(x1,y1)],[(x0,y0),(x1,y1)],...]
xy = xy.reshape(-1, 1, 2)
segments = np.hstack([xy[:-1], xy[1:]])

fig, ax = plt.subplots()
coll = LineCollection(segments, cmap=plt.cm.gist_ncar)
coll.set_array(np.random.random(xy.shape[0]))

ax.add_collection(coll)
ax.autoscale_view()

plt.show()
```
For both of these cases, we're just drawing random colors from the "gist_ncar" coloramp. Have a look at the colormaps here (gist_ncar is about 2/3 of the way down): http://matplotlib.org/examples/color/colormaps_reference.html


Question:
Coloring axis/tick labels How would one color y-axis label and tick labels in red? So for example the "y-label" and values 0 through 40, to be colored in red.
```
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

fig = plt.figure()
ax = plt.subplot(111)
ax.set_ylabel("y-label")

for i in xrange(5):
    ax.plot(x, i * x, label='$y = %ix$' % i)

ax.legend()

plt.show()
```

Response:
The xlabel can be colorized when setting it,
```
ax.set_xlabel("x-label", color="red")
```
For setting the ticklabels' color, one may either use tick_params, which sets the ticklabels' as well as the ticks' color
```
ax.tick_params(axis='x', colors='red')
```
Alternatively, plt.setp can be used to only set the ticklabels' color, without changing the ticks' color.
```
plt.setp(ax.get_xticklabels(), color="red")
```
Note that for changing the properties on the y-axis, one can replace the x with a y in the above.


Question:
How to store an image in a variable I would like to store the image generated by matplotlib in a variable raw_data to use it as inline image.
```
import os
import sys
os.environ['MPLCONFIGDIR'] = '/tmp/'
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

print "Content-type: image/png\n"
plt.plot(range(10, 20))

raw_data = plt.show()

if raw_data:
    uri = 'data:image/png;base64,' + urllib.quote(base64.b64encode(raw_data))
    print '<img src = "%s"/>' % uri
else:
    print "No data"

#plt.savefig(sys.stdout, format='png')
```
None of the functions suit my use case: plt.savefig(sys.stdout, format='png') - Writes it to stdout. This does help.. as I have to embed the image in a html file. plt.show() / plt.draw() does nothing when executed from command line

Response:
Have you tried cStringIO or an equivalent?
```
import os
import sys
import matplotlib
import matplotlib.pyplot as plt
import StringIO
import urllib, base64

plt.plot(range(10, 20))
fig = plt.gcf()

imgdata = StringIO.StringIO()
fig.savefig(imgdata, format='png')
imgdata.seek(0)  # rewind the data

print "Content-type: image/png\n"
uri = 'data:image/png;base64,' + urllib.quote(base64.b64encode(imgdata.buf))
print '<img src = "%s"/>' % uri
```


Question: multidimensional confidence intervals [closed] Closed. This question needs to be more focused. It is not currently accepting answers. Want to improve this question? Guide the asker to update the question so it focuses on a single, specific problem. Narrowing the question will help others answer the question concisely. You may edit the question if you feel you can improve it yourself. If edited, the question will be reviewed and might be reopened. Closed 4 years ago. Improve this question I have numerous tuples (par1,par2), i.e. points in a 2 dimensional parameter space obtained from repeating an experiment multiple times. I'm looking for a possibility to calculate and visualize confidence ellipses (not sure if thats the correct term for this). Here an example plot that I found in the web to show what I mean: source: blogspot.ch/2011/07/classification-and-discrimination-with.html So in principle one has to fit a multivariate normal distribution to a 2D histogram of data points I guess. Can somebody help me with this?

Response:
It sounds like you just want the 2-sigma ellipse of the scatter of points? If so, consider something like this (From some code for a paper here: https://github.com/joferkington/oost_paper_code/blob/master/error_ellipse.py):
```
import numpy as np

import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse

def plot_point_cov(points, nstd=2, ax=None, **kwargs):
    """
    Plots an `nstd` sigma ellipse based on the mean and covariance of a point
    "cloud" (points, an Nx2 array).

    Parameters
    ----------
        points : An Nx2 array of the data points.
        nstd : The radius of the ellipse in numbers of standard deviations.
            Defaults to 2 standard deviations.
        ax : The axis that the ellipse will be plotted on. Defaults to the
            current axis.
        Additional keyword arguments are pass on to the ellipse patch.

    Returns
    -------
        A matplotlib ellipse artist
    """
    pos = points.mean(axis=0)
    cov = np.cov(points, rowvar=False)
    return plot_cov_ellipse(cov, pos, nstd, ax, **kwargs)

def plot_cov_ellipse(cov, pos, nstd=2, ax=None, **kwargs):
    """
    Plots an `nstd` sigma error ellipse based on the specified covariance
    matrix (`cov`). Additional keyword arguments are passed on to the
    ellipse patch artist.

    Parameters
    ----------
        cov : The 2x2 covariance matrix to base the ellipse on
        pos : The location of the center of the ellipse. Expects a 2-element
            sequence of [x0, y0].
        nstd : The radius of the ellipse in numbers of standard deviations.
            Defaults to 2 standard deviations.
        ax : The axis that the ellipse will be plotted on. Defaults to the
            current axis.
        Additional keyword arguments are pass on to the ellipse patch.

    Returns
    -------
        A matplotlib ellipse artist
    """
    def eigsorted(cov):
        vals, vecs = np.linalg.eigh(cov)
        order = vals.argsort()[::-1]
        return vals[order], vecs[:,order]

    if ax is None:
        ax = plt.gca()

    vals, vecs = eigsorted(cov)
    theta = np.degrees(np.arctan2(*vecs[:,0][::-1]))

    # Width and height are "full" widths, not radius
    width, height = 2 * nstd * np.sqrt(vals)
    ellip = Ellipse(xy=pos, width=width, height=height, angle=theta, **kwargs)

    ax.add_artist(ellip)
    return ellip

if __name__ == '__main__':
    #-- Example usage -----------------------
    # Generate some random, correlated data
    points = np.random.multivariate_normal(
            mean=(1,1), cov=[[0.4, 9],[9, 10]], size=1000
            )
    # Plot the raw points...
    x, y = points.T
    plt.plot(x, y, 'ro')

    # Plot a transparent 3 standard deviation covariance ellipse
    plot_point_cov(points, nstd=3, alpha=0.5, color='green')

    plt.show()
```


Question:
How to align axis label to the right or top in matplotlib? By default matplotlib plots the axis label at the center of the axis. I would like to move the label in such way that it is aligned with the end of the axis, both for the horizontal and vertical axis. For example for the horizontal axis I would like to see:
```
+--------------------+
|                    |
|                    |
|                    |
|                    |
|                    |
+--------------------+
                 label
```
Is it possibile to do it with the global setting of matplotlib?

Response:
UPDATE Current 2023's Matplotlib has a new keyword loc=… for plt.[xy]label. From xlabel doc string loc : {'left', 'center', 'right'}, The label position. This is a high-level alternative for passing parameters *x* and *horizontalalignment*. and you can write simply
```
plt.xlabel('x_description', loc='right')
plt.ylabel('y_description', loc='top')
```
My other answer is still a good one, because the idea of getting an object, modifying it and setting it back is a good idea on its own, but here it is an alternative, cleaner solution:
```
...
plt.xlabel('x_description', horizontalalignment='right', x=1.0)
plt.ylabel('y_description', horizontalalignment='right', y=1.0)
...
```
as you can see, no more magic numbers, and works both for xlabel and ylabel. Note that in both cases we are going to change the horizontal alignment, for reasons that were eventually clear to me when I first changed the vertical alignment in ylabel...


Question:
How to change the line color in seaborn linear regression jointplot As described in the seaborn API the following code will produce a linear regression plot.
```
import numpy as np, pandas as pd; np.random.seed(0)
import seaborn as sns; sns.set(style="white", color_codes=True)
tips = sns.load_dataset("tips")
g = sns.jointplot(x="total_bill", y="tip", data=tips, kind='reg')
sns.plt.show()
```
However, with a lot of data points the regression line is not really visible anymore. How can I change its color? I could not find a builtin seaborn command. In case the line is in the background (i.e. behind the dots), I would also like to ask how to bring it to the front.

Response:
There are a couple approaches, as mwaskom tactfully pointed out. You can pass arguments to the joint plot, but setting color there affects the whole scatterplot:
```
import numpy as np, pandas as pd; np.random.seed(0)
import seaborn as sns#; sns.set(style="white", color_codes=True)
tips = sns.load_dataset("tips")
g = sns.jointplot(x="total_bill", y="tip", data=tips, kind='reg',
                  joint_kws={'color':'green'}) # Scatter and regression all green
```
Or pass a dictionary of line-plotting keywords through that dictionary of scatterplot keywords. I read seaborn/linearmodels.py to figure out where to do this, which was entertaining and informative in itself. Dict in dict:
```
g = sns.jointplot(x="total_bill", y="tip", data=tips, kind='reg',
                  joint_kws={'line_kws':{'color':'cyan'}}) # Only regression cyan
```
Or you can access the line after it's been plotted and change it directly. This depends on the regression line being the first line plotted, so could break with seaborn updates. It's also aesthetically/pedagogically different, as you don't recolor the uncertainty spread. It is a good way to get familiar with what the JointGrid object is and how else you might interact with it. (And maybe there are properties you can't set with the function call arguments, although I can't think of any.)
```
g = sns.jointplot(x="total_bill", y="tip", data=tips, kind='reg')
regline = g.ax_joint.get_lines()[0]
regline.set_color('red')
regline.set_zorder(5)
```


Question:
3d surface from a rectangular array of heights I am trying to plot some HDF data in matplotlib. After importing them using h5py, the data is stored in a form of array, like this:
```
array([[151, 176, 178],
       [121, 137, 130],
       [120, 125, 126])
```
In this case, x and y values are just the indexes of the array's fields, while z value is the value of specific field. In the (x,y,z) form it would look like:
```
(1,1,151)
(2,1,176)
(3,1,178)
(1,2,121)
...
```
and so on. Is there an easy way to do a surface plot from this kind of data? I know I can change this to (x,y,z) tuples by iterating all over the array, but maybe it is not needed?

Response:
If you want a 3-d surface plot, you have to create the meshgrid first. You can try:
```
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

X = np.arange(1, 10)
Y = np.arange(1, 10)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='hot', linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)

fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
```
which will generate, However, if the only relevant information is in the z-values, you can simply use imshow. Here, z-values are represented by their color. You can achieve this by:
```
im = plt.imshow(Z, cmap='hot')
plt.colorbar(im, orientation='horizontal')
plt.show()
```
Which will give,


Question:
Two different color colormaps in the same imshow matplotlib Let's suppose the example below
```
import matplotlib.pyplot as plt
import numpy as np

v1 = -1 + 2*np.random.rand(50,150)
fig = plt.figure()
ax = fig.add_subplot(111)
p = ax.imshow(v1,interpolation='nearest')
cb = plt.colorbar(p,shrink=0.5)
plt.xlabel('Day')
plt.ylabel('Depth')
cb.set_label('RWU')
plt.show()
```
I want to show the values below zero in a different colormap than the values above zero

Response:
First of all, is it possible that you just want to use a diverging colormap, 'neutral' at zero, and diverging to two distinct colours? This is an example:
```
import matplotlib.pyplot as plt
import numpy as np

v1 = -1+2*np.random.rand(50,150)
fig,ax = plt.subplots()
p = ax.imshow(v1,interpolation='nearest',cmap=plt.cm.RdBu)
cb = plt.colorbar(p,shrink=0.5)
ax.set_xlabel('Day')
ax.set_ylabel('Depth')
cb.set_label('RWU')
plt.show()
```
If you really want to use two different colormaps, this is a solution with masked arrays:
```
import matplotlib.pyplot as plt
import numpy as np
from numpy.ma import masked_array

v1 = -1+2*np.random.rand(50,150)
v1a = masked_array(v1,v1<0)
v1b = masked_array(v1,v1>=0)
fig,ax = plt.subplots()
pa = ax.imshow(v1a,interpolation='nearest',cmap=cm.Reds)
cba = plt.colorbar(pa,shrink=0.25)
pb = ax.imshow(v1b,interpolation='nearest',cmap=cm.winter)
cbb = plt.colorbar(pb,shrink=0.25)
plt.xlabel('Day')
plt.ylabel('Depth')
cba.set_label('positive')
cbb.set_label('negative')
plt.show()
```


Question:
obtain the max y-value of a histogram I am looking for suggestions on how to calculate the maximum y-value of a histogram.
```
#simple histogram. how can I obtain the maximum value of, say, x and y?

import matplotlib.pyplot as plt
hdata = randn(500)
x = plt.hist(hdata)
y = plt.hist(hdata, bins=40)
```

Response:
hist returns a tuple that contains the histogram bin locations and y values. Try this:
```
y, x, _ = plt.hist(hdata)

print x.max()
print y.max()
```
Note that len(y) = len(x) - 1.


Question:
Line colour of 3D parametric curve in python's matplotlib.pyplot I've been googling quite some time with no success ... maybe my keywords are just lousy. Anyway, suppose I have three 1D numpy.ndarrays of the same length I'd like to plot them in 3D as a trajectory. Moreover, I'd like to be able to do either of the following things: Change the colour of the line as a function of z Change the colour of the line as a function of time (i.e. the index in the arrays) This demo has an example of making such a curve:
```
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.gca(projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
ax.plot(x, y, z)

plt.show()
```
But how do I achieve 1 or 2? Solutions to only one or the other are welcome! Thanks in advance.

Response:
As with normal 2d plots, you cannot have a gradient of color along an ordinary line. However, you can do it with scatter:
```
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.gca(projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)

#1 colored by value of `z`
ax.scatter(x, y, z, c = plt.cm.jet(z/max(z)))

#2 colored by index (same in this example since z is a linspace too)
N = len(z)
ax.scatter(x, y, z, c = plt.cm.jet(np.linspace(0,1,N)))

plt.show()
```
I liked @Junuxx's hack so I applied it here:
```
for i in xrange(N-1):
    ax.plot(x[i:i+2], y[i:i+2], z[i:i+2], color=plt.cm.jet(255*i/N))
```


Question:
Plotting distance arrows in technical drawing I want to indicate a distance in one of my plots. What I have in mind is the way they do it in technical drawings, showing a double headed arrow with the distance as text beside it. Example:
```
from matplotlib.pyplot import *

hlines(7,0,2, linestyles='dashed')
hlines(11,0,2, linestyles='dashed')
hlines(10,0,2, linestyles='dashed')
hlines(8,0,2, linestyles='dashed')
plot((1,1),(8,10), 'k',) # arrow line
plot((1,1),(8,8), 'k', marker='v',) # lower arrowhead
plot((1,1),(10,10), 'k', marker='^',) # upper arrowhead
text(1.1,9,"D=1")
```
This results in something like this (two of the hlines are not really needed, they just increase the drawing area...): Is there a quicker way to do this, preferably with arrowheads which end on the exact spot, not below/above where they should be? Extra points for placing the text automatically as well. Edit: I had been playing with annotate but since the string would have to be sacrificed this solution had lost some appeal to me. Thanks for pointing out the arrowstyle though, it wasn't working when I attempted something similar. I guess there is no way around writing a little function to do it with one call...

Response:
```
import matplotlib.pyplot as plt

plt.hlines(7, 0, 2, linestyles='dashed')
plt.hlines(11, 0, 2, linestyles='dashed')
plt.hlines(10, 0, 2, linestyles='dashed')
plt.hlines(8, 0, 2, linestyles='dashed')
plt.annotate(
    '', xy=(1, 10), xycoords='data',
    xytext=(1, 8), textcoords='data',
    arrowprops={'arrowstyle': '<->'})
plt.annotate(
    'D = 1', xy=(1, 9), xycoords='data',
    xytext=(5, 0), textcoords='offset points')

# alternatively,
# plt.text(1.01, 9, 'D = 1')

plt.show()
```
yields For more information on the many options available with plt.annotate, see this page. As shown above, the text can be placed with either plt.annotate or plt.text. With plt.annotate you can specify the offset (e.g. (5, 0)) in points, whereas with plt.text you can specify the text location in data coordinates (e.g. (1.01, 9)).


Question:
How to change the range of the x-axis and y-axis I am new to matlibplot and I'm trying to draw a circle with radius 1 but have both my x and y axis go from 0 to 3 with an increment of 0.25. Right now, I have drawn the graph and the circle but my x and y axis only go from 0 to 1, so there is little room left either above, below, to the left, or to the right of the circle. Here's the code so far:
```
import numpy as np
    import matplotlib.pyplot as plt
    import scipy, pylab

    plt.axes()
    circle=plt.Circle((0, 0), radius=1, fc='w')
    plt.gca().add_patch(circle)
    plt.yticks(np.arange(0, 3, 0.25))
    plt.xticks(np.arange(0, 3, 0.25))
    plt.axis('scaled')
    plt.show()
```
I've looked at the following questions, but found them either to be a little too advanced for what I'm trying to accomplish or just a tad bit off-topic:
```
http://stackoverflow.com/questions/27170139/how-to-change-the-range-of-my-x-axis-in-matplotlib

    http://stackoverflow.com/questions/22642511/change-y-range-to-start-from-0-with-matplotlib

   http://stackoverflow.com/questions/27456185/scaling-axis-for-a-scatter-plot-in-matlibplot-in-python

   http://stackoverflow.com/questions/22642511/change-y-range-to-start-from-0-with-matplotlib
```
What I want to do now is, while keeping my circle in the same place on the graph, increase the range of my x and y axis from 0-1 to 0-3 while keeping the increment of 0.25 on each axis, allowing me to plot points all around the edge of the circle without having to worry about the top, bottom, or either side of the circle touching either of the two axis. I've looked through the matlibplot documentation, but can't seem to find a simple step-by-step explanation of how to change the spacing on my axis. Any insight on this would be brilliant! Thanks in advance!

Response:
To change the axes range, you can use
```
plt.xlim([-3, 3])
plt.ylim([-3, 3])
```
You will then have to remove the line plt.axis('scaled') for this to work.
```
import numpy as np
import matplotlib.pyplot as plt
import scipy, pylab

plt.axes()
circle=plt.Circle((0, 0), radius=1, fc='w')
plt.gca().add_patch(circle)
plt.xlim([-3, 3])
plt.ylim([-3, 3])
plt.yticks(np.arange(-3, 3, 0.25))
plt.xticks(np.arange(-3, 3, 0.25))
plt.show()
```


Question:
How to deal with NaN values when plotting a boxplot I am using matplotlib to plot a box figure but there are some missing values (NaN). Then I found it doesn't display the box figure within the columns having NaN values. Do you know how to solve this problem? Here are the codes.
```
import numpy as np
import matplotlib.pyplot as plt

#==============================================================================
# open data
#==============================================================================
filename='C:\\Users\\liren\\OneDrive\\Data\\DATA in the first field-final\\ks.csv'

AllData=np.genfromtxt(filename,delimiter=";",skip_header=0,dtype='str')

TreatmentCode = AllData[1:,0]
RepCode = AllData[1:,1]
KsData= AllData[1:,2:].astype('float')
DepthHeader = AllData[0,2:].astype('float')
TreatmentUnique = np.unique(TreatmentCode)[[3,1,4,2,8,6,9,7,0,5,10],]
nT = TreatmentUnique.size#nT=number of treatments
#nD=number of deepth;nR=numbers of replications;nT=number of treatments;iT=iterms of treatments
nD = 5
nR = 6
KsData_3D = np.zeros((nT,nD,nR))

for iT in range(nT):
    Treatment = TreatmentUnique[iT]

    TreatmentFilter = TreatmentCode == Treatment

    KsData_Filtered = KsData[TreatmentFilter,:]

    KsData_3D[iT,:,:] = KsData_Filtered.transpose()iD = 4

fig=plt.figure()
ax = fig.add_subplot(111)
plt.boxplot(KsData_3D[:,iD,:].transpose())
ax.set_xticks(range(1,nT+1))
ax.set_xticklabels(TreatmentUnique)
ax.set_title(DepthHeader[iD])
```
Here is the final figure and some of the treatments are missing in the box.

Response:
You can remove the NaNs from the data first, then plot the filtered data. To do that, you can first find the NaNs using np.isnan(data), then perform the bitwise inversion of that Boolean array using the ~: bitwise inversion operator. Use that to index the data array, and you filter out the NaNs.
```
filtered_data = data[~np.isnan(data)]
```
In a complete example (adapted from here) Tested in python 3.10, matplotlib 3.5.1, seaborn 0.11.2, numpy 1.21.5, pandas 1.4.2 For 1D data:
```
import matplotlib.pyplot as plt
import numpy as np

# fake up some data
np.random.seed(2022)  # so the same data is created each time
spread = np.random.rand(50) * 100
center = np.ones(25) * 50
flier_high = np.random.rand(10) * 100 + 100
flier_low = np.random.rand(10) * -100
data = np.concatenate((spread, center, flier_high, flier_low), 0)

# Add a NaN
data[40] = np.NaN

# Filter data using np.isnan
filtered_data = data[~np.isnan(data)]

# basic plot
plt.boxplot(filtered_data)

plt.show()
```
For 2D data: For 2D data, you can't simply use the mask above, since then each column of the data array would have a different length. Instead, we can create a list, with each item in the list being the filtered data for each column of the data array. A list comprehension can do this in one line: [d[m] for d, m in zip(data.T, mask.T)]
```
import matplotlib.pyplot as plt
import numpy as np

# fake up some data
np.random.seed(2022)  # so the same data is created each time
spread = np.random.rand(50) * 100
center = np.ones(25) * 50
flier_high = np.random.rand(10) * 100 + 100
flier_low = np.random.rand(10) * -100
data = np.concatenate((spread, center, flier_high, flier_low), 0)

data = np.column_stack((data, data * 2., data + 20.))

# Add a NaN
data[30, 0] = np.NaN
data[20, 1] = np.NaN

# Filter data using np.isnan
mask = ~np.isnan(data)
filtered_data = [d[m] for d, m in zip(data.T, mask.T)]

# basic plot
plt.boxplot(filtered_data)

plt.show()
```
I'll leave it as an exercise to the reader to extend this to 3 or more dimensions, but you get the idea. The solution above is how to do this using matplotlib alone. Other alternatives (that use matplotlib under the hood) are available that have this behaviour built in, so no need to filter the data yourself. Use seaborn, which is a high-level API for matplotlib. seaborn.boxplot filters NaN under the hood.
```py
import seaborn as sns

sns.boxplot(data=data)
```
1D 2D Use pandas. NaN is also ignored if plotting from df.plot(kind='box') for pandas, which uses matplotlib as the default plotting backend.
```py
import pandas as pd

df = pd.DataFrame(data)

df.plot(kind='box')
```
1D 2D


Question:
Showing a simple matplotlib plot in plotly Dash Is it possible to show a simple matplotlib plot (the kind usually generated by plt.show()) in plotly's Dash framework? Or just plotly-like graphs with plotly's Scatters and Data traces? Specifically I guess I need a different component than Graph (see below) and a way to return the simple plot in the update_figure function. Example:
```
import dash
import dash_core_components as dcc
import dash_html_components as html
import numpy as np
import matplotlib.pyplot as plt

app = dash.Dash()

app.layout = html.Div(children=[
    html.H1(children='Hello Dash'),

    dcc.Slider(
        id='n_points',
        min=10,
        max=100,
        step=1,
        value=50,
    ),

    dcc.Graph(id='example') # or something other than Graph?...
])

@app.callback(
    dash.dependencies.Output('example', 'figure'),
    [dash.dependencies.Input('n_points', 'value')]
)

def update_figure(n_points):
    #create some matplotlib graph
    x = np.random.rand(n_points)
    y = np.random.rand(n_points)
    plt.scatter(x, y)
    # plt.show()
    return None # return what, I don't know exactly, `plt`?

if __name__ == '__main__':
    app.run_server(debug=True)
```

Response:
If you don't want an interactive plot, you can return a static one (found from this help)
```py
import io
import base64

...

app.layout = html.Div(children=[
    ...,

    html.Img(id='example') # img element
])

@app.callback(
    dash.dependencies.Output('example', 'src'), # src attribute
    [dash.dependencies.Input('n_points', 'value')]
)
def update_figure(n_points):
    #create some matplotlib graph
    x = np.random.rand(n_points)
    y = np.random.rand(n_points)
    buf = io.BytesIO() # in-memory files
    plt.scatter(x, y)
    plt.savefig(buf, format = "png")
    plt.close()
    data = base64.b64encode(buf.getbuffer()).decode("utf8") # encode to html elements
    buf.close()
    return "data:image/png;base64,{}".format(data)
```


Question:
Create a color generator from given colormap in matplotlib I have a series of lines that each need to be plotted with a separate colour. Each line is actually made up of several data sets (positive, negative regions etc.) and so I'd like to be able to create a generator that will feed one colour at a time across a spectrum, for example the gist_rainbow map shown here. I have found the following works but it seems very complicated and more importantly difficult to remember,
```
from pylab import *

NUM_COLORS = 22

mp = cm.datad['gist_rainbow']
get_color = matplotlib.colors.LinearSegmentedColormap.from_list(mp, colors=['r', 'b'], N=NUM_COLORS)
...
# Then in a for loop
    this_color = get_color(float(i)/NUM_COLORS)
```
Moreover, it does not cover the range of colours in the gist_rainbow map, I have to redefine a map. Maybe a generator is not the best way to do this, if so what is the accepted way?

Response:
To index colors from a specific colormap you can use:
```
import pylab
NUM_COLORS = 22

cm = pylab.get_cmap('gist_rainbow')
for i in range(NUM_COLORS):
    color = cm(1.*i/NUM_COLORS)  # color will now be an RGBA tuple

# or if you really want a generator:
cgen = (cm(1.*i/NUM_COLORS) for i in range(NUM_COLORS))
```


Question: Repeating x axis labels for all facets using FacetGrid in seaborn I am working with the FacetGrid example presented here that results in the plot below. In my data set, there is quite a lot of plots, and it would be convenient to have the x axis labels repeated for each facet, not only at the bottom. For this example, the values 62, ..., 76 should be repeated for each of the A-J facets.

Response:
The answer by Bazingaa works for matplotlib version 2.0.2. For newer versions of matplotlib, using ax.tick_params() and setting labelbottom=True seems to work:
```
for ax in g.axes.flatten():
    ax.tick_params(labelbottom=True)
```


Question:
Plot feature importance with xgboost When I plot the feature importance, I get this messy plot. I have more than 7000 variables. I understand the built-in function only selects the most important, although the final graph is unreadable. This is the complete code:
```
import numpy as np
import pandas as pd
df = pd.read_csv('ricerice.csv')
array=df.values
X = array[:,0:7803]
Y = array[:,7804]
from xgboost import XGBClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
seed=0
test_size=0.30
X_train, X_test, y_train, y_test = train_test_split(X,Y,test_size=test_size, random_state=seed)
from xgboost import XGBClassifier
model = XGBClassifier()
model.fit(X, Y)
import matplotlib.pyplot as plt
from matplotlib import pyplot
from xgboost import plot_importance
fig1=plt.gcf()
plot_importance(model)
plt.draw()
fig1.savefig('xgboost.png', figsize=(50, 40), dpi=1000)
```
Although the size of the figure, the graph is illegible.

Response:
There are couple of points: To fit the model, you want to use the training dataset (X_train, y_train), not the entire dataset (X, y). You may use the max_num_features parameter of the plot_importance() function to display only top max_num_features features (e.g. top 10). With the above modifications to your code, with some randomly generated data the code and output are as below:
```
import numpy as np

# generate some random data for demonstration purpose, use your original dataset here
X = np.random.rand(1000,100)     # 1000 x 100 data
y = np.random.rand(1000).round() # 0, 1 labels

from xgboost import XGBClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
seed=0
test_size=0.30
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=test_size, random_state=seed)
from xgboost import XGBClassifier
model = XGBClassifier()
model.fit(X_train, y_train)
import matplotlib.pylab as plt
from matplotlib import pyplot
from xgboost import plot_importance
plot_importance(model, max_num_features=10) # top 10 most important features
plt.show()
```


Question: Flier colors in boxplot with matplotlib According to the documentation, the Axes.boxplot function takes a dictionary flierprop as argument to define the properties of the outliers. Unfortunately, I can't find the documentation concerning this dictionary. In particular, I would like to define the color of the border of the marker. By default, empty circles are drawn. One can set the face color, as shown in the example. Nevertheless, the circle border is always a black line. I tried with the keys color and markercolor (the former has no effect, the latter produces an error). What should I do to set a color for the marker line?

Response:
To set marker color use property markerfacecolor but for border color - markeredgecolor:
```
import matplotlib.pyplot as plt
import numpy as np

# fake up some data
spread = np.random.rand(50) * 100
center = np.ones(25) * 50
flier_high = np.random.rand(10) * 100 + 100
flier_low = np.random.rand(10) * -100
data = np.concatenate((spread, center, flier_high, flier_low), 0)

# plot. Set color of marker edge
flierprops = dict(marker='o', markerfacecolor='r', markersize=12,
                  linestyle='none', markeredgecolor='g')
plt.boxplot(data, flierprops=flierprops)

plt.show()
```
According to @Spiros the flierprops dictionary is documented here like other boxplot properties: http://matplotlib.org/users/dflt_style_changes.html?highlight=flierprops#boxplot


Question:
Please explain in detail 2D Histogram in Python I am trying to understand what are the values of a 2D histogram. I have 2 numpy arrays of the same length X and Y (float numbers in each one). For example the first 10 values of X: [ 88, 193, 60, 98, 78, 100, 75, 76, 130] and Y: [ 18. , 9. , 36.1, 18.5, 34.3, 32.9, 32.2, 22. , 15. ] When I use:
```
import matplotlib.pyplot as plt

plt.hist2d(X,Y, bins=(10,20))
```
I get a 2D histogram. But what does it mean? 1D histogram simply shows me how much of each item I have. Please explain me what does it mean in 2D. Thanks in advance!

Response:
Suppose you have a 1D array, you plot the position of its values on the x axis, they are so dense that you can't tell the spatial distribution, you use a 1D histogram to show the distribution by count of boxes along the x axis. Problem solved. Then you have two 1D arrays, a list of 2D dots in (x, y) axes. You plot their positions on the x-y plane, again they are so dense and overlap with each other. You want to view the distribution better by count of boxes in the plane, so you try a 2D diagram. Problem solved. Here is an example
```
import numpy as np
import matplotlib.pyplot as plt

%matplotlib inline

# prepare 2D random dots centered at (0, 0)
n = 100000
x = np.random.randn(n)
y = x + np.random.randn(n)

# plot data
fig1 = plt.figure()
plt.plot(x,y,'.r')
plt.xlabel('x')
plt.ylabel('y')
```
gives
```
# plot 2D histogram using pcolor
fig2 = plt.figure()
plt.hist2d(x, y, bins=100)
plt.xlabel('x')
plt.ylabel('y')
cbar = plt.colorbar()
cbar.ax.set_ylabel('Counts')
```
gives


Question:
How to create a polar contour plot Update: I've done a full write-up of the way I found to do this on my blog at http://blog.rtwilson.com/producing-polar-contour-plots-with-matplotlib/ - you may want to check there first. I'm trying to plot a polar contour plot in matplotlib. I've found various resources on the internet, (a) I can't seem to get my code to work and (b) many of the resources appear rather old, and I'm wondering if there is a better way now. For example, http://www.mail-archive.com/[email protected]/msg01953.html suggests that something may be done to improve things soon, and that was in 2006! I'd love to be able to plot proper polar contour plots - like pcolor lets you do for its type of plot (see commented out section below), but I can't seem to find any way to do that, so I'm converting to cartesian co-ordinates first. Anyway, I have the code that follows:
```
from pylab import *
import numpy as np

azimuths = np.arange(0, 360, 10)
zeniths = np.arange(0, 70, 10)
values = []

for azimuth in azimuths:
  for zenith in zeniths:
    print "%i %i" % (azimuth, zenith)
    # Run some sort of model and get some output
    # We'll just use rand for this example
    values.append(rand())

theta = np.radians(azimuths)

values = np.array(values)
values = values.reshape(len(zeniths), len(azimuths))

# This (from http://old.nabble.com/2D-polar-surface-plot-td28896848.html)
# works fine
##############
# Create a polar axes
# ax = subplot(111, projection='polar')
# pcolor plot onto it
# c = ax.pcolor(theta, zeniths, values)
# show()

r, t = np.meshgrid(zeniths, azimuths)

x = r*np.cos(t)
y = r*np.sin(t)

contour(x, y, values)
```
When I run that I get an error TypeError: Inputs x and y must be 1D or 2D.. I'm not sure why I get this, as both x and y are 2D. Am I doing something wrong? Also, it seems rather clunky to be putting my values returned from my model into a list and then reshaping it. Is there a better way to do this?

Response:
You should just be able to use ax.contour or ax.contourf with polar plots just as you normally would... You have a few bugs in your code, though. You convert things to radians, but then use the values in degrees when you plot. Also, you're passing in r, theta to contour when it expects theta, r. As a quick example:
```
import numpy as np
import matplotlib.pyplot as plt

#-- Generate Data -----------------------------------------
# Using linspace so that the endpoint of 360 is included...
azimuths = np.radians(np.linspace(0, 360, 20))
zeniths = np.arange(0, 70, 10)

r, theta = np.meshgrid(zeniths, azimuths)
values = np.random.random((azimuths.size, zeniths.size))

#-- Plot... ------------------------------------------------
fig, ax = plt.subplots(subplot_kw=dict(projection='polar'))
ax.contourf(theta, r, values)

plt.show()
```


Question:
Multivariate (polynomial) best fit curve in python? How do you calculate a best fit line in python, and then plot it on a scatterplot in matplotlib? I was I calculate the linear best-fit line using Ordinary Least Squares Regression as follows:
```
from sklearn import linear_model
clf = linear_model.LinearRegression()
x = [[t.x1,t.x2,t.x3,t.x4,t.x5] for t in self.trainingTexts]
y = [t.human_rating for t in self.trainingTexts]
clf.fit(x,y)
regress_coefs = clf.coef_
regress_intercept = clf.intercept_
```
This is multivariate (there are many x-values for each case). So, X is a list of lists, and y is a single list. For example:
```
x = [[1,2,3,4,5], [2,2,4,4,5], [2,2,4,4,1]]
y = [1,2,3,4,5]
```
But how do I do this with higher order polynomial functions. For example, not just linear (x to the power of M=1), but binomial (x to the power of M=2), quadratics (x to the power of M=4), and so on. For example, how to I get the best fit curves from the following? Extracted from Christopher Bishops's "Pattern Recognition and Machine Learning", p.7:

Response:
The accepted answer to this question provides a small multi poly fit library which will do exactly what you need using numpy, and you can plug the result into the plotting as I've outlined below. You would just pass in your arrays of x and y points and the degree(order) of fit you require into multipolyfit. This returns the coefficients which you can then use for plotting using numpy's polyval. Note: The code below has been amended to do multivariate fitting, but the plot image was part of the earlier, non-multivariate answer.
```
import numpy
import matplotlib.pyplot as plt
import multipolyfit as mpf

data = [[1,1],[4,3],[8,3],[11,4],[10,7],[15,11],[16,12]]
x, y = zip(*data)
plt.plot(x, y, 'kx')

stacked_x = numpy.array([x,x+1,x-1])
coeffs = mpf(stacked_x, y, deg)
x2 = numpy.arange(min(x)-1, max(x)+1, .01) #use more points for a smoother plot
y2 = numpy.polyval(coeffs, x2) #Evaluates the polynomial for each x2 value
plt.plot(x2, y2, label="deg=3")
```
Note: This was part of the answer earlier on, it is still relevant if you don't have multivariate data. Instead of coeffs = mpf(..., use coeffs = numpy.polyfit(x,y,3) For non-multivariate data sets, the easiest way to do this is probably with numpy's polyfit: numpy.polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False) Least squares polynomial fit. Fit a polynomial p(x) = p[0] * x**deg + ... + p[deg] of degree deg to points (x, y). Returns a vector of coefficients p that minimises the squared error.


Question: Python - animation with matplotlib.pyplot How can one create animated diagrams using popular matplotlib library? I am particularly interested in animated gifs.

Response: The matplotlib docs provide an entire section of examples on animation (see this scipy tutorial also). Most, however, involve using the various GUI widget backends. There is one in there, "movie demo", that shows how to produce an avi of a series of PNGS. To produce animated GIFs, I think your options are pretty limited. Last I checked, PIL didn't support them. You could however generate a series of PNGs using pyplot's savefig and then stitch them together using a call to ImageMagick or mencoder.


Question: Plotting 3-tuple data points in a surface / contour plot using matplotlib I have some surface data that is generated by an external program as XYZ values. I want to create the following graphs, using matplotlib: Surface plot Contour plot Contour plot overlayed with a surface plot I have looked at several examples for plotting surfaces and contours in matplotlib - however, the Z values seems to be a function of X and Y i.e. Y ~ f(X,Y). I assume that I will somehow need to transform my Y variables, but I have not seen any example yet, that shows how to do this. So, my question is this: given a set of (X,Y,Z) points, how may I generate Surface and contour plots from that data? BTW, just to clarify, I do NOT want to create scatter plots. Also although I mentioned matplotlib in the title, I am not averse to using rpy(2), if that will allow me to create these charts.

Response:
for do a contour plot you need interpolate your data to a regular grid http://www.scipy.org/Cookbook/Matplotlib/Gridding_irregularly_spaced_data a quick example:
```

```python
xi = linspace(min(X), max(X))
```

```python
yi = linspace(min(Y), max(Y))
```

```python
zi = griddata(X, Y, Z, xi, yi)
```

```python
contour(xi, yi, zi)
#Output
#```
#for the surface http://matplotlib.sourceforge.net/examples/mplot3d/surface3d_demo.html
#```
```

```python
from mpl_toolkits.mplot3d import Axes3D
```

```python
fig = figure()
```

```python
ax = Axes3D(fig)
```

```python
xim, yim = meshgrid(xi, yi)
```

```python
ax.plot_surface(xim, yim, zi)
```

```python
show()
```

```python
help(meshgrid(x, y))
#Output
#    Return coordinate matrices from two coordinate vectors.
#    [...]
#    Examples
#    --------
#    >>> X, Y = np.meshgrid([1,2,3], [4,5,6,7])
#    >>> X
#    array([[1, 2, 3],
#           [1, 2, 3],
#           [1, 2, 3],
#           [1, 2, 3]])
#    >>> Y
#    array([[4, 4, 4],
#           [5, 5, 5],
#           [6, 6, 6],
#           [7, 7, 7]])
#```
#contour in 3D http://matplotlib.sourceforge.net/examples/mplot3d/contour3d_demo.html
#```
```

```python
fig = figure()
```

```python
ax = Axes3D(fig)
```

```python
ax.contour(xi, yi, zi) # ax.contourf for filled contours
```

```python
show()
#Output
#```
```


Question:
How to use Matplotlib in Django? From some examples from the Internet I made the test code below. It works! ... BUT if I reload the page, the pie will draw itself with the same image. Some parts get darker every time I reload the page. When I restart the the development server, it is reset. How do I draw properly with Matplotlib in Django? It looks like it remembers some drawings... Source views.py (let urls.py link to it):
```
from pylab import figure, axes, pie, title
from matplotlib.backends.backend_agg import FigureCanvasAgg

def test_matplotlib(request):
    f = figure(1, figsize=(6,6))
    ax = axes([0.1, 0.1, 0.8, 0.8])
    labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
    fracs = [15,30,45, 10]
    explode=(0, 0.05, 0, 0)
    pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
    title('Raining Hogs and Dogs', bbox={'facecolor':'0.8', 'pad':5})

    canvas = FigureCanvasAgg(f)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
```
I am using Django 1.0.1 and Python 2.6.2 (Linux).

Response:
You need to remove the num parameter from the figure constructor and close the figure when you're done with it.
```
import matplotlib.pyplot

def test_matplotlib(request):
    f = figure(figsize=(6,6))
    ....
    matplotlib.pyplot.close(f)
```
By removing the num parameter, you'll avoid using the same figure at the same time. This could happen if 2 browsers request the image at the same time. If this is not an issue, another possible solution is to use the clear method, i.e. f.clear().


Question:
MatplotLib 'saveFig()' Fullscreen I used MatplotLib with Cartopy to generate some data images. The problem is that when I set the frame size to fullscreen and use plt.show() the image is perfect and the resolution is fine. However, when I save this figure using 'plt.savefig()' the image saved keeps with its original size (not fullscreen). Showing outcome images: My code is the following: def plot_tec_cartopy(descfile): global matrixLon, matrixLat, matrixTec
```
ax = plt.axes(projection=cartopy.crs.PlateCarree())

v = np.linspace(0, 80, 46, endpoint=True)
cp = plt.contourf(matrixLon, matrixLat, matrixTec, v, cmap=plt.cm.rainbow)
plt.clim(0, 80)
plt.colorbar(cp)

ax.add_feature(cartopy.feature.COASTLINE)
ax.add_feature(cartopy.feature.BORDERS, linestyle=':')
ax.set_extent([-85, -30, -60, 15])

# Setting X and Y labels using LON/LAT format
ax.set_xticks([-85, -75, -65, -55, -45, -35])
ax.set_yticks([-60, -55, -50, -45, -40, -35, -30, -25, -20, -15, -10, -5, 0, 5, 10, 15])
lon_formatter = LongitudeFormatter(number_format='.0f',
                                   degree_symbol='',
                                   dateline_direction_label=True)
lat_formatter = LatitudeFormatter(number_format='.0f',
                                  degree_symbol='')
ax.xaxis.set_major_formatter(lon_formatter)
ax.yaxis.set_major_formatter(lat_formatter)

plt.title('Conteúdo Eletrônico Total', style='normal', fontsize='12')

# Acquiring Date
year, julianday = check_for_zero(descfile.split('.')[2]), descfile.split('.')[3]
hour, minute = descfile.split('.')[4], descfile.split('.')[5].replace('h','')
date = datetime.datetime(int(year), 1, 1, int(hour), int(minute)) + datetime.timedelta(int(julianday)-1)
month = date.month
day = date.day

# Set common labels
ax.text(1.22, 1.05, 'TEC', style='normal',
    verticalalignment='top', horizontalalignment='right',
    transform=ax.transAxes,
    color='black', fontsize=11)
ax.text(1, 0.005, 'EMBRACE/INPE', style='italic',
    verticalalignment='bottom', horizontalalignment='right',
    transform=ax.transAxes,
    color='black', fontsize=10)
ax.text(1, 0.995, str(date) + ' UT', style='italic',
    verticalalignment='top', horizontalalignment='right',
    transform=ax.transAxes,
    color='black', fontsize=10)
ax.text(0.5, -0.08, 'Copyright \N{COPYRIGHT SIGN} 2017 INPE - Instituto Nacional de',
    style='oblique', transform=ax.transAxes,
    verticalalignment='bottom', horizontalalignment='center',
    color='black', fontsize=8)
ax.text(0.5, -0.108, 'Pesquisas Espacias. Todos direitos reservados',
    style='oblique', transform=ax.transAxes,
    verticalalignment='bottom', horizontalalignment='center',
    color='black', fontsize=8)

manager = plt.get_current_fig_manager()
manager.resize(*manager.window.maxsize())

figName = 'tec.map' + '.' + str(year) + '.' + str(julianday) + '.' + str(hour) + '.' + str(minute) + 'h.png'
#plt.show()
plt.savefig(figName, dpi=500)
plt.clf()
```
Maybe I need to set some parameter into savefig() to say it that it needs to save my modified frame? Can someone help me with this issue? Thanks in advance.

Response:
Coming from MATLAB, it is not intuitive that your displayed figure does not have to affect the saved one in terms of dimensions, etc. Each one is handled by a different backend, and you can modify the dpi and size_inches as you choose. Increasing the DPI is definitely going to help you get a large figure, especially with a format like PNG, which does not know about the size in inches. However, it will not help you scale the text relative to the figure itself. To do that, you will have to use the object oriented API, specifically, figure.set_size_inches, which I don't think has an equivalent in plt. Replace
```
plt.savefig(figName, dpi=500)
```
with
```
fig = plt.gcf()
fig.set_size_inches((8.5, 11), forward=False)
fig.savefig(figName, dpi=500)
```
The size 8.5, 11 is the width and height of the standard paper size in the US, respectively. You can set it to whatever you want. For example, you can use your screen size, but in that case be sure to get the DPI right as well.


Question: Is it possible to set the marker edge alpha in Matplotlib? For example, say I want to plot with color='None' but markeredgecolor='mediumseagreen' with the edges having alpha=0.5. Is that possible?

Response:
As answered in the comments: Either pass the color as an RGBA tuple or get the RGBA value from colorConverter:
```
matplotlib.colors.colorConverter.to_rgba('mediumseagreen', alpha=.5)
```


Question:
Vertical xtick labels on top, not bottom I want to plot a confusion matrix using Pylab. The class labels along the horizontal axis are long, so I want to plot them rotated vertically. However, I also want to plot them on top of the axis, not below. This command can plot vertical labels on bottom:
```
pylab.imshow(confusion_matrix)
pylab.xticks(..., rotation='vertical')
```
and this command can plot horizontal labels on top without rotation:
```
pylab.matshow(confusion_matrix)
```
but I cannot find anything that does both. The following command does not work.
```
pylab.matshow(confusion_matrix)
pylab.xticks(..., rotation='vertical')
```
Can you suggest a way to plot a confusion matrix with xticks on top of the axis with vertical rotation? Thank you. EDIT Thank you, Mark, for your help. It got me on the right track by inspecting the tick properties more closely. The only difference with your answer and my desired answer is applying that idea to an AxesImage, not a plot. After investigation, here is the answer:
```
im = pylab.matshow(confusion_matrix)
for label in im.axes.xaxis.get_ticklabels():
    label.set_rotation(90)
im.figure.show()
```
To those reading... don't forget about show()! I forgot that I needed to refresh the figure. See output below. Confusion matrix with vertical labels. http://up.stevetjoa.com/rotate_ticklabels.png

Response:
If I understand you correctly, this will get you close. You might have to 'pad' your labels out with spaces to move them off the xaxis line.
```
from matplotlib import pylab
pylab.plot([0, 6], [0, 6])
pylab.xticks([1,2,3,4,5,6],('one','two','three','four','five','six'),rotation='vertical',verticalalignment='bottom')
```
EDIT IN RESPONSE TO COMMENT If you want them rotated vertical on the top x-axis, try this:
```
pylab.plot([0, 6], [0, 6])
pylab.xticks([1,2,3,4,5,6],('one','two','three','four','five','six'))
for tick in pylab.gca().xaxis.iter_ticks():
    tick[0].label2On = True
    tick[0].label1On = False
    tick[0].label2.set_rotation('vertical')
```


Question:
Interchange location of y and z axis in a 3D plot By default, plotting a set of points (or whatever) in 3D with matplotlib, locates the z axis vertically, as seen here (code below): I need to interchange the z and y axis, so that that y axis is shown vertically. I've looked around but found no way to tell matplotlib to do this. Add: I do not want to have to resort to a hack where I interchange the data and labels. This is a simple 3 points 3D plot, but I have to plot much more complicated surfaces. I'm looking for a general solution, not just something that works with scatter plots. A simple way to tell matplotlib to put the y axis vertically instead of the z axis is the clean way to do it. MWE
```
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = Axes3D(fig)

ax.scatter([0.2, 0.5, 0.8], [2.3, 0.47, 1.], [2.1, 5.3, 0.7])

ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()
```

Response: I don't think that this is currently possible. ax.view_init() would need to accept a third angle too. I opened an issue over at github, https://github.com/matplotlib/matplotlib/issues/14453#issue-452397120, let's hope someone is committed to implement this feature. Update The third view angle was recently implemented and has been merged into the matplotlib main branch: https://github.com/matplotlib/matplotlib/pull/21426 It should appear in Matplotlib 3.6.0.


Question:
Implementing an iterator in Julia for an animation with PyPlot I am just trying to reproduce this simple example of an animation in Matplotlib but using PyPlot in Julia. I am having difficulties with the definition of the iterator simData() that is passed to the function funcAnimation , because it seems that PyPlot doesn't recognize the iterator that I defined in Julia (via a Task) as such. Here is my approach to define the same function simData():
```
function simData()

    t_max = 10.0
    dt = 0.05
    x = 0.0
    t = 0.0

    function it()
        while t < t_max
            x = sin(pi*t)
            t = t+dt
            produce(x,t)
        end
    end
    Task(it)
end
```
As you can check, this kind of iterator yields in theory the same values than the python simData() generator of the example (try for example collect(simData()). However, I got this error when I try to do the animation
```
LoadError: PyError (:PyObject_Call) <type 'exceptions.TypeError'>
TypeError('PyCall.jlwrap object is not an iterator',)
  File "/usr/local/lib/python2.7/dist-packages/matplotlib/animation.py", line 1067, in __init__
    TimedAnimation.__init__(self, fig, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/matplotlib/animation.py", line 913, in __init__
    *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/matplotlib/animation.py", line 591, in __init__
    self._init_draw()
  File "/usr/local/lib/python2.7/dist-packages/matplotlib/animation.py", line 1092, in _init_draw
    self._draw_frame(next(self.new_frame_seq()))

while loading In[5], in expression starting on line 42

 in pyerr_check at /home/diegotap/.julia/v0.4/PyCall/src/exception.jl:56
 [inlined code] from /home/diegotap/.julia/v0.4/PyCall/src/exception.jl:81
 in pycall at /home/diegotap/.julia/v0.4/PyCall/src/PyCall.jl:402
 in call at /home/diegotap/.julia/v0.4/PyCall/src/PyCall.jl:429
```
As I mentioned, I think the problem is that the Julia iterator is not recognized as such by Python. Do you have any idea about how to fix that? PS: Here is a Jupyter notebook with the full code that I used to do the animation.

Response:
In your code, you invoke FuncAnimation() this way:
```
ani = anim.FuncAnimation(fig, simPoints, simData, blit = false, interval=10, repeat= true)
```
In the original code, simData() was a generator, but in your code it isn't, it returns a generator, so I'd expect your code to invoke it this way:
```
ani = anim.FuncAnimation(fig, simPoints, simData(), blit = false, interval=10, repeat= true)
```
Let's finish the problem -- since we can't get Python to recognize the return value of simData() as an iterator, we'll ignore that feature and have simPoints() call simData() to launch the task and then return a function for Python to animate:
```
using PyCall
using PyPlot
pygui(true)

@pyimport matplotlib.animation as animation

function simData()
    t_max = 10.0
    dt = 0.05
    x = 0.0
    t = -dt

    function it()
        while t < t_max
            x = sin(pi * t)
            t = t + dt
            produce(x, t)
        end
    end

    Task(it)
end

function simPoints()
    task = simData()

    function points(frame_number)
        x, t = consume(task)
        line[:set_data](t, x)
        return(line, "")
    end

    points
end

figure = plt[:figure]()
axis = figure[:add_subplot](111)
line = axis[:plot]([], [], "bo", ms = 10)[1]
axis[:set_ylim](-1, 1)
axis[:set_xlim](0, 10)

ani = animation.FuncAnimation(figure, simPoints(), blit=false, interval=10, frames=200, repeat=false)

plt[:show]()
```
This works for one pass of the bouncing ball across the graph and stops when it hits the right edge (unlike the original Python which repeats).


Question:
Why does matplotlib require setting log scale before plt.scatter() but not plt.plot()? I found out in this helpful answer that plt.scatter() and plt.plot() behave differently when a logrithmic scale is used on the y axis. With plot, I can change to log any time before I use plt.show(), but log has to be set up-front, before the scatter method is used. Is this just a historical and irreversible artifact in matplotlib, or is this in the 'unexpected behavior' category?
```
import matplotlib.pyplot as plt

X = [0.997, 2.643, 0.354, 0.075, 1.0, 0.03, 2.39, 0.364, 0.221, 0.437]
Y = [15.487507, 2.320735, 0.085742, 0.303032, 1.0, 0.025435, 4.436435,
     0.025435, 0.000503, 2.320735]

plt.figure()

plt.subplot(2,2,1)
plt.scatter(X, Y)
plt.xscale('log')
plt.yscale('log')
plt.title('scatter - scale last')

plt.subplot(2,2,2)
plt.plot(X, Y)
plt.xscale('log')
plt.yscale('log')
plt.title('plot - scale last')

plt.subplot(2,2,3)
plt.xscale('log')
plt.yscale('log')
plt.scatter(X, Y)
plt.title('scatter - scale first')

plt.subplot(2,2,4)
plt.xscale('log')
plt.yscale('log')
plt.plot(X, Y)
plt.title('plot - scale first')

plt.show()
```

Response:
This somehow has to do with the the display area (axes limits) calculated by matplotlib. This behaviour is fixed by manually editing the axes range by using set_xlim and set_ylim methods.
```
plt.figure()
plt.scatter(X, Y)
plt.yscale('log')
plt.xscale('log')
axes = plt.gca()
axes.set_xlim([min(X),max(X)])
axes.set_ylim([min(Y),max(Y)])
plt.show()
```
The exact reason of this behavior is however not yet figured out by me. Suggestions are welcomed. EDIT As mentioned in comments section, apparently Matplotlib has identified Autoscaling has fundamental problems as a Release Critical Issue on their official Github repo, which would be fixed in upcoming versions. Thanks.


Question:
Plot Feature Importance with feature names In R there are pre-built functions to plot feature importance of Random Forest model. But in python such method seems to be missing. I search for a method in matplotlib. model.feature_importances gives me following:
```
array([  2.32421835e-03,   7.21472336e-04,   2.70491223e-03,
         3.34521084e-03,   4.19443238e-03,   1.50108737e-03,
         3.29160540e-03,   4.82320256e-01,   3.14117333e-03])
```
Then using following plotting function:
```
>> pyplot.bar(range(len(model.feature_importances_)), model.feature_importances_)
>> pyplot.show()
```
I get a barplot but I would like to get barplot with labels while importance showing horizontally in a sorted fashion. I am also exploring seaborn and was not able to find a method.

Response:
Quick answer for data scientists that ain't got no time to waste: Load the feature importances into a pandas series indexed by your column names, then use its plot method. For a classifier model trained using X:
```
feat_importances = pd.Series(model.feature_importances_, index=X.columns)
feat_importances.nlargest(20).plot(kind='barh')
```
Slightly more detailed answer with a full example: Assuming you trained your model with data contained in a pandas dataframe, this is fairly painless if you load the feature importance into a panda's series, then you can leverage its indexing to get the variable names displayed easily. The plot argument kind='barh' gives us a horizontal bar chart, but you could easily substitute this argument for kind='bar' for a traditional bar chart with the feature names along the x-axis if you prefer. nlargest(n) is a pandas Series method which will return a subset of the series with the largest n values. This is useful if you've got lots of features in your model and you only want to plot the most important. A quick complete example using the classic Kaggle Titanic dataset...
```
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
%matplotlib inline            # don't forget this if you're using jupyter!

X = pd.read_csv("titanic_train.csv")
X = X[['Pclass', 'Age', 'Fare', 'Parch', 'SibSp', 'Survived']].dropna()
y = X.pop('Survived')

model = RandomForestClassifier()
model.fit(X, y)

(pd.Series(model.feature_importances_, index=X.columns)
   .nlargest(4)
   .plot(kind='barh'))        # some method chaining, because it's sexy!
```
Which will give you this:


Question:
Set yaxis of all subplots to the same range - Matplotlib I'm wondering how do I force my subplots to share the y-axis range. This is my code:
```
f, axes = plt.subplots(7, 1, sharex='col', sharey='row', figsize=(15, 30))
distance = []

for i in range(simulations):
    delta = numpy.zeros((simulations+samples, simulations+samples))
    data_x = sample_x[i*samples:(i*samples)+samples] + ensamble_x
    data_y = sample_y[i*samples:(i*samples)+samples] + ensamble_y
    for j in range(simulations+samples):
        for k in range(simulations+samples):
            if j <= k:
                dist = similarity_measure((data_x[j].flatten(), data_y[j].flatten()), (data_x[k].flatten(), data_y[k].flatten()))
                delta[j, k] = delta[k, j] = dist

    delta = 1-((delta+1)/2)
    delta /= numpy.max(delta)
    model = manifold.TSNE(n_components=2, random_state=0, metric='precomputed')
    coords = model.fit_transform(delta)

    mds = manifold.MDS(n_components=2, max_iter=3000, eps=1e-9, random_state=0,
                   dissimilarity="precomputed", n_jobs=1)
    coords = mds.fit(delta).embedding_

    close, far = find_distance(coords[:samples, :], coords[samples+i, :])

    distance.append((close, far))

    axes[i].scatter(coords[:samples, 0], coords[:samples, 1], marker='x', c=colors[i], s=50, edgecolor='None')
    axes[i].scatter(coords[samples:, 0], coords[samples:, 1], marker='o', c=colors,    s=50, edgecolor='None')

    axes[i].scatter(coords[close, 0], coords[close, 1], marker='s', facecolor="none", c=colors[i], s=50, edgecolor='None')
    axes[i].scatter(coords[far, 0]  , coords[far, 1]  , marker='s', facecolor="none", c=colors[i], s=50, edgecolor='None')

    axes[i].set_title('Simulation '+str(i+1), fontsize=20)

markers = []
labels = [str(n+1) for n in range(simulations)]
for i in range(simulations):
     markers.append(Line2D([0], [0], linestyle='None', marker="o", markersize=10, markeredgecolor="none", markerfacecolor=colors[i]))
lgd = plt.legend(markers, labels, numpoints=1, bbox_to_anchor=(1.0, -0.055), ncol=simulations)
plt.tight_layout()
plt.ylim(-1, 1)
plt.axis('equal')
plt.savefig('Simulations.pdf', bbox_extra_artists=(lgd,), format='pdf', bbox_inches='tight')
```
And it's result: As can be seen, the y axis limits differs from one subplot to another. I'd like to use the max/min range generated. Thank you. EDTI: MINIMAL EXAMPLE
```
%matplotlib inline

from sklearn.preprocessing import normalize
from sklearn import manifold
from matplotlib import pyplot as plt
from matplotlib.lines import Line2D

import numpy
import itertools

f, axes = plt.subplots(7, 1, sharex='col', sharey='row', figsize=(15, 30))
distance = []

for i in range(7):
    delta = numpy.random.randint(0, 100, (100, 100))

    axes[i].scatter(delta[:, 0], delta[:, 1], marker='x', c='r', s=50, edgecolor='None')

    axes[i].set_title('Simulation '+str(i+1), fontsize=20)
    axes[i].set_ylim(0, 100)

markers = []

plt.tight_layout()
plt.axis('equal')
```

Response:
Your 1st line
```
f, axes = plt.subplots(7, 1, sharex='col', sharey='row', figsize=(15, 30))
```
has an inappropriate value for the sharey parameter. Using sharey='row' you're asking that all the subplots in each row share the same y axis, but each of your subplots is in a row by itself, so you see no sharing. If you try sharey=True or sharey='col' you'll get what you want. Addendum The following code
```

```python
a = np.random.random(21)
```

```python
b = a+5
```

```python
x = np.arange(21)
```

```python
f, (ax, bx) = plt.subplots(2,1,sharey='row') # like yours
```

```python
ax.plot(x,a)
#Output
#[<matplotlib.lines.Line2D at 0x7f5b98004f98>]
```

```python
bx.plot(x,b)
#Output
#[<matplotlib.lines.Line2D at 0x7f5b980238d0>]
```

```python
f, (ax, bx) = plt.subplots(2,1,sharey='col') # like mine
```

```python
ax.plot(x,a)
#Output
#[<matplotlib.lines.Line2D at 0x7f5b94764dd8>]
```

```python
bx.plot(x,b)
#Output
#[<matplotlib.lines.Line2D at 0x7f5b98038198>]
```

```python
```
gives me the following two plots. Can you spot a single difference?
```


Question:
Python legend attribute error Why am I getting an error here that relates to the plt.plot label?
```
fig = plt.figure()
ax = plt.gca()
barplt = plt.bar(bins,frq,align='center',label='Dgr')
normplt = plt.plot(bins_n,frq_n,'--r', label='Norm');
ax.set_xlim([min(bins)-1, max(bins)+1])
ax.set_ylim([0, max(frq)])
plt.xlabel('Dgr')
plt.ylabel('Frequency')
plt.show()
plt.legend(handles=[barplt,normplt])
```
This is the error that I get: 'list' object has no attribute 'get_label'

Response:
Because plt.plot can plot more than one line at once, it returns a list of line2D objects, even if you only plot one line (i.e. in your case, a list of length 1). When you grab its handle for the legend, you want to only use the first item of this list (the actual line2D object). There are (at least) two ways you can resolve this: 1) add a comma after normplt when you call plt.plot, to only store the first item from the list in normplt
```
barplt = plt.bar(bins,frq,width,align='center',label='Dgr')
normplt, = plt.plot(bins_n,frq_n,'--r', label='Norm')   # note the comma after normplt

print normplt
# Line2D(Norm)    <-- This is the line2D object, not a list, so we can use it in legend
...
plt.legend(handles=[barplt,normplt])
```
2) Use only the first item in the list when you call plt.legend (normplt[0]):
```
barplt = plt.bar(bins,frq,width,align='center',label='Dgr')
normplt = plt.plot(bins_n,frq_n,'--r', label='Norm')

print normplt
# [<matplotlib.lines.Line2D object at 0x112076710>]
# Note, this is a list containing the Line2D object. We just want the object,
# so we can use normplt[0] in legend
...
plt.legend(handles=[barplt,normplt[0]])
```


Question:
Use Line2D to plot line in matplotlib I have the data:
```
x = [10,24,23,23,3]
y = [12,2,3,4,2]
```
I want to plot it using matplotlib.lines.Line2D(xdata, ydata). I tried:
```
import matplotlib.lines
matplotlib.lines.Line2D(x, y)
```
But how do I show the line?

Response:
You should add the line to a plot and then show it:
```

```python
import matplotlib.pyplot as plt
```

```python
from matplotlib.lines import Line2D
```

```python
fig = plt.figure()
```

```python
ax = fig.add_subplot(111)
```

```python
x = [10,24,23,23,3]
```

```python
y = [12,2,3,4,2]
```

```python
line = Line2D(x, y)
```

```python
ax.add_line(line)
#Output
#<matplotlib.lines.Line2D at 0x7f4c10732f60>
```

```python
ax.set_xlim(min(x), max(x))
#Output
#(3, 24)
```

```python
ax.set_ylim(min(y), max(y))
#Output
#(2, 12)
```

```python
plt.show()
```
The result:
```


Question:
python matplotlib histogram specify different colours for different bars I want to colour different bars in a histogram based on which bin they belong to. e.g. in the below example, I want the first 3 bars to be blue, the next 2 to be red, and the rest black (the actual bars and colour is determined by other parts of the code). I can change the colour of all the bars using the color option, but I would like to be able to give a list of colours that are used.
```
import numpy as np
import matplotlib.pyplot as plt

data = np.random.rand(1000)
plt.hist(data,color = 'r')
```

Response:
One way may be similar to approach in other answer:
```
import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
data = np.random.rand(1000)

N, bins, patches = ax.hist(data, edgecolor='white', linewidth=1)

for i in range(0,3):
    patches[i].set_facecolor('b')
for i in range(3,5):
    patches[i].set_facecolor('r')
for i in range(5, len(patches)):
    patches[i].set_facecolor('black')

plt.show()
```
Result:


Question:
bar plot xtick frequency I want to create a simple bar chart for pandas DataFrame object. However, the xtick on the chart appears to be too granular, whereas if I change the plot to line chart, xtick is optimized for better viewing. I was wondering if I can bring the same line chart xtick frequency to bar chart? Thanks.
```
locks.plot(kind='bar',y='SUM')
```
EDIT Resultant plot:

Response:
You can reduce the number of thicks by setting one every n ticks, doing something like:
```
n = 10

ax = locks.plot(kind='bar', y='SUM')
ticks = ax.xaxis.get_ticklocs()
ticklabels = [l.get_text() for l in ax.xaxis.get_ticklabels()]
ax.xaxis.set_ticks(ticks[::n])
ax.xaxis.set_ticklabels(ticklabels[::n])

ax.figure.show()
```


Question: How to set the default figure size and DPI of all plots drawn by `matplotlib.pyplot` I know how to set figure size and DPI of one plot by fig, ax = plt.figure(figsize=(8,8), dpi=140). But I am wondering there is a way that can change the figure size or DPI of all plots without specifying these values each time. Could anyone help me？ Thanks in advance.

Response:
For your specific case, you probably want to set
```
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = [8.0, 8.0]
plt.rcParams['figure.dpi'] = 140
```
This will change the default for this one script. However, there are a number of ways how you can change the defaults permanently. You could modify the matplotlibrc file or create your own style sheet. Please refer to the matplotlib documentation for details: https://matplotlib.org/tutorials/introductory/customizing.html https://matplotlib.org/users/dflt_style_changes.html


Question:
Seaborn Catplot set values over the bars I plotted a catplot in seaborn like this
```
import seaborn as sns
import pandas as pd

data  = {'year': [2016, 2013, 2014, 2015, 2016, 2013, 2014, 2015, 2016, 2013, 2014, 2015, 2016, 2013, 2014, 2015, 2016, 2013, 2014, 2015], 'geo_name': ['Michigan', 'Michigan', 'Michigan', 'Michigan', 'Washtenaw County, MI', 'Washtenaw County, MI', 'Washtenaw County, MI', 'Washtenaw County, MI', 'Ann Arbor, MI', 'Ann Arbor, MI', 'Ann Arbor, MI', 'Ann Arbor, MI', 'Philadelphia, PA', 'Philadelphia, PA', 'Philadelphia, PA', 'Philadelphia, PA', 'Ann Arbor, MI Metro Area', 'Ann Arbor, MI Metro Area', 'Ann Arbor, MI Metro Area', 'Ann Arbor, MI Metro Area'], 'geo': ['04000US26', '04000US26', '04000US26', '04000US26', '05000US26161', '05000US26161', '05000US26161', '05000US26161', '16000US2603000', '16000US2603000', '16000US2603000', '16000US2603000', '16000US4260000', '16000US4260000', '16000US4260000', '16000US4260000', '31000US11460', '31000US11460', '31000US11460', '31000US11460'], 'income': [50803.0, 48411.0, 49087.0, 49576.0, 62484.0, 59055.0, 60805.0, 61003.0, 57697.0, 55003.0, 56835.0, 55990.0, 39770.0, 37192.0, 37460.0, 38253.0, 62484.0, 59055.0, 60805.0, 61003.0], 'income_moe': [162.0, 163.0, 192.0, 186.0, 984.0, 985.0, 958.0, 901.0, 2046.0, 1688.0, 1320.0, 1259.0, 567.0, 424.0, 430.0, 511.0, 984.0, 985.0, 958.0, 901.0]}
df = pd.DataFrame(data)

g = sns.catplot(x='year', y='income', data=df, kind='bar', hue='geo_name', legend=True)
g.fig.set_size_inches(15,8)
g.fig.subplots_adjust(top=0.81,right=0.86)
```
I am getting an output like shown below I want to add the values of each bar on its top in K representation. For example in 2013 the bar for Michigan is at 48411 so I want to add the value 48.4K on top of that bar. Likewise for all the bars.

Response:
Use matplotlib.pyplot.bar_label as of matplotlib v3.4.2 See Adding value labels on a matplotlib bar chart for other plotting options related to the new method. See the matplotlib: Bar Label Demo page for additional formatting options. Use the fmt parameter for simple formats, and the labels parameter for customized string formatting. For horizontal bars, use v.get_width instead of v.get_height. Tested in python 3.11, pandas 1.5.3, matplotlib 3.7.1, seaborn 0.12.2 For single plot only
```py
g = sns.catplot(data=df, x='year', y='income', kind='bar', hue='geo_name', legend=True, height=6, aspect=2)

# extract the matplotlib axes_subplot objects from the FacetGrid
ax = g.facet_axis(0, 0)  # or ax = g.axes.flat[0]

# iterate through the axes containers
for c in ax.containers:
    labels = [f'{(v.get_height() / 1000):.1f}K' for v in c]
    ax.bar_label(c, labels=labels, label_type='edge')
```
For single or multiple plots
```py
g = sns.catplot(data=df, x='year', y='income', kind='bar', col='geo_name', col_wrap=3)

g.fig.subplots_adjust(top=0.9)
g.fig.suptitle('Bar Count with Annotations')

# iterate through axes
for ax in g.axes.ravel():

    # add annotations
    for c in ax.containers:
        labels = [f'{(v.get_height() / 1000):.1f}K' for v in c]
        ax.bar_label(c, labels=labels, label_type='edge')
    ax.margins(y=0.2)

plt.show()
```
Also works for grouped bars in Facets (subplots)
```py
df = sns.load_dataset('titanic')
g = sns.catplot(data=df, kind='count', x='survived', hue='sex', col='class')

# iterate through axes
for ax in g.axes.ravel():

    # add annotations
    for c in ax.containers:
        # add custom labels with the labels=labels parameter if needed
        # labels = [f'{h}' if (h := v.get_height()) > 0 else '' for v in c]
        ax.bar_label(c, label_type='edge')
    ax.margins(y=0.2)
```


Question:
Ordering and Formatting Dates on X-Axis in Seaborn Bar Plot This seems so simple, but for the life of me I can't figure it out. I am new to Python and Seaborn, and I am doing all this online at PythonAnywhere. All I am trying to do is create a simple barplot in seaborn, with dates ordered properly (that is, ascending from left to right), on the x-axis. When I try this:
```
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime
import pandas as pd
import seaborn as sns

emp = pd.DataFrame([[32, "5/31/2018"], [3, "2/28/2018"], [40, "11/30/2017"], [50, "8/31/2017"], [51, "5/31/2017"]],
               columns=["jobs", "12monthsEnding"])

fig = plt.figure(figsize = (10,7))

sns.barplot(x = "12monthsEnding", y = "uniqueClientExits", data = emp,
estimator = sum, ci = None)

fig.autofmt_xdate()
plt.show()
```
I get this: Nice looking bar graph but with the dates ordered descending from left to right And then when I try to convert the objects to datetime: (note: i'm using pd.to_datetime() below in order to try and recreate what happens when I use parse_dates in pd.read_csv(), which is how I'm actually creating the dataframe.)
```
emp = pd.DataFrame([[32, pd.to_datetime("5/31/2018")], [3, pd.to_datetime("2/28/2018")], [40, pd.to_datetime("11/30/2017")], [50, pd.to_datetime("8/31/2017")], [51, pd.to_datetime("5/31/2017")]],
               columns=["jobs", "12monthsEnding"])

fig = plt.figure(figsize = (10,7))

sns.barplot(x = "12monthsEnding", y = "uniqueClientExits", data = emp,
estimator = sum, ci = None)

fig.autofmt_xdate()

plt.show()
```
I get this: Bar plot with the dates in the right order, but WRONG format I get the same bar plot, with the dates ordered properly, but in the full, long datetime format, with the time, etc. But all I want is the day/month/year. I've scoured stackoverflow for two days now and nothing has worked. I'm starting to wonder if part of the reason is because I'm working on PythonAnywhere. But I also can't find any reason why that would be. This is driving me nuts. Looking forward to any assistance. Thanks.

Response:
Using your second approach, simply sort and reformat the datetime values to YYYY-MM-DD and pass values into set_xticklabels. Below demonstrates with random, seeded data:
```
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns

# RANDOM DATA
np.random.seed(62918)
emp = pd.DataFrame({'uniqueClientExits': [np.random.randint(15) for _ in range(50)],
                    '12monthsEnding': pd.to_datetime(
                                          np.random.choice(
                                              pd.date_range('2018-01-01', periods=50),
                                          50)
                                      )
                   }, columns = ['uniqueClientExits','12monthsEnding'])

# PLOTTING
fig, ax = plt.subplots(figsize = (12,6))
fig = sns.barplot(x = "12monthsEnding", y = "uniqueClientExits", data = emp,
                  estimator = sum, ci = None, ax=ax)

x_dates = emp['12monthsEnding'].dt.strftime('%Y-%m-%d').sort_values().unique()
ax.set_xticklabels(labels=x_dates, rotation=45, ha='right')
```
To check graph output, run a groupby().sum():
```
print(emp.groupby('12monthsEnding').sum().head())

#                 uniqueClientExits
# 12monthsEnding
# 2018-01-01                     12
# 2018-01-02                      4
# 2018-01-04                     11
# 2018-01-06                     13
# 2018-01-08                     10
# 2018-01-11                     11
# 2018-01-14                      9
# 2018-01-15                      0
# 2018-01-16                      4
# 2018-01-17                      5
# ...
```


Question: Controlling alpha value on 3D scatter plot using Python and matplotlib I'm plotting a 3D scatter plot using the function scatter and mplot3d. I'm choosing a single color for all points in the plot, but when drawn by matplotlib the transparency of the points is set relative to the distance from the camera. Is there any way to disable this feature? I've tried setting the alpha kwarg to None/1 and also set vmin/vmax to 1 (in an attempt to force the color scaling to be a solid single color) with no luck. I didn't see any other likely options related to this setting in the scatter documentation. Thanks!

Response:
For Matplotlib 1.4+, the answer provided below by @fraxel is the best solution: call ax.scatter with the argument depthshade=False. There is no arguments that can control this. Here is some hack method. Disable set_edgecolors and set_facecolors method, so that mplot3d can't update the alpha part of the colors:
```
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.gca(projection='3d')

x = np.random.sample(20)
y = np.random.sample(20)
z = np.random.sample(20)
s = ax.scatter(x, y, z, c="r")
s.set_edgecolors = s.set_facecolors = lambda *args:None

ax.legend()
ax.set_xlim3d(0, 1)
ax.set_ylim3d(0, 1)
ax.set_zlim3d(0, 1)

plt.show()
```
If you want call set_edgecolors and set_facecolors methods later, you can backup these two methods before disable them:
```
s._set_facecolors, s._set_edgecolors = s.set_facecolors, s.set_edgecolors
```


Question:
How to add a legend to matplotlib pie chart? Using this example http://matplotlib.org/examples/pie_and_polar_charts/pie_demo_features.html how could I add a legend to this pie chart? My problem is that I have One big slice 88.4%, the second largest slice is 10.6%, and the other slices are 0.7 and 0.3%. The labels around the pie don't appear (except for the biggest slice) and neither the percentage values for the smaller slices. So I guess I can add a legend showing the names and the values. But I haven't found out how...
```
# -*- coding: UTF-8 -*-
import matplotlib.pyplot as plt
# The slices will be ordered and plotted counter-clockwise.
labels = 'Rayos X', 'RMN en solución', 'Microscopía electrónica', 'Otros'
sizes = [88.4, 10.6, 0.7, 0.3]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
explode = (0.1, 0, 0, 0)
plt.pie(sizes, explode=explode, labels=labels, colors=colors, shadow=True, startangle=90)
plt.legend(title="técnica")
# Set aspect ratio to be equal so that pie is drawn as a circle.
plt.axis('equal')
plt.show()
```

Response:
I checked your code, and the plt.legend() creates a legend, just how you want it to be; maybe set the loc="lower left", so it does not overlap with the relevant pieces of pie. For me, the strings are displayed properly, besides the non standard chars - which might cause the problem that they are not displayed to you at all. Only the biggest slice and "Otros" do not contain special chars. Maybe also try to resize the figure, as they might be pushed out of the canvas. Please refer to how to write accents with matplotlib and try again with proper strings. The percentages are not shown, because you did not set them to be shown. Please refer to the example posted by you, as you omitted autopct='%1.1f%%'which will plot the percentages. In this special case, I would rather not plot the percentages, as they will overlap just like the labels on the border, as some slices are too small. Maybe add these information to the legend. Putting it all together (besides the special chars - I had some problems activating TeX), try the following code:
```
# -*- coding: UTF-8 -*-
import matplotlib.pyplot as plt
# The slices will be ordered and plotted counter-clockwise.
labels = [r'Rayos X (88.4 %)', r'RMN en solucion (10.6 %)',
r'Microscopia electronica (0.7 %)', r'Otros (0.3 %)']
sizes = [88.4, 10.6, 0.7, 0.3]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
patches, texts = plt.pie(sizes, colors=colors, startangle=90)
plt.legend(patches, labels, loc="best")
# Set aspect ratio to be equal so that pie is drawn as a circle.
plt.axis('equal')
plt.tight_layout()
plt.show()
```


Question:
Plotting animated quivers in Python I am trying to animate a vector such as wind in Python. I tried to use quiver function in pylab and in combination with matplotlib.animation from matplotlib. However, the result says 'QuiverKey' object is not subscriptable. I think that it is because I don't understand fully about these two functions or just these two functions don't match together. Below is my code, it is actually the combination between quiver and animation functions from matplotlib.
```
def update_line(num, data, line):
    line.set_data(data[...,:num])
    return line,

X,Y = np.meshgrid(np.arange(0,2*np.pi,.2),np.arange(0,2*np.pi,.2) )
U = np.cos(X)
V = np.sin(Y)

fig1 = plt.figure()
Q = quiver( X[::3, ::3], Y[::3, ::3], U[::3, ::3], V[::3, ::3],
        pivot='mid', color='r', units='inches' )
data = quiverkey(Q, 0.5, 0.03, 1, r'$1 \frac{m}{s}$', fontproperties={'weight': 'bold'})
plt.axis([-1, 7, -1, 7])
title('scales with plot width, not view')
l, = plt.plot([], [], 'r-')
plt.xlabel('x')
plt.ylabel('y')
plt.title('test')
line_ani = animation.FuncAnimation(fig1, update_line, 25, fargs=(data, l),
interval=50, blit=True)
plt.show()
```

Response:
Here's an example to get you started:
```
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

X, Y = np.mgrid[:2*np.pi:10j,:2*np.pi:5j]
U = np.cos(X)
V = np.sin(Y)

fig, ax = plt.subplots(1,1)
Q = ax.quiver(X, Y, U, V, pivot='mid', color='r', units='inches')

ax.set_xlim(-1, 7)
ax.set_ylim(-1, 7)

def update_quiver(num, Q, X, Y):
    """updates the horizontal and vertical vector components by a
    fixed increment on each frame
    """

    U = np.cos(X + num*0.1)
    V = np.sin(Y + num*0.1)

    Q.set_UVC(U,V)

    return Q,

# you need to set blit=False, or the first set of arrows never gets
# cleared on subsequent frames
anim = animation.FuncAnimation(fig, update_quiver, fargs=(Q, X, Y),
                               interval=50, blit=False)
fig.tight_layout()
plt.show()
```


Question: Discretized continuous Fourier transform with numpy Consider a function f(t), how do I compute the continuous Fouriertransform g(w) and plot it (using numpy and matplotlib)? This or the inverse problem (g(w) given, plot of f(t) unknown) occurs if there exists no analytical solution to the Fourier Integral.

Response:
You can use the numpy FFT module for that, but have to do some extra work. First let's look at the Fourier integral and discretize it: Here k,m are integers and N the number of data points for f(t). Using this discretization we get The sum in the last expression is exactly the Discrete Fourier Transformation (DFT) numpy uses (see section "Implementation details" of the numpy FFT module). With this knowledge we can write the following python script
```
import numpy as np
import matplotlib.pyplot as pl

#Consider function f(t)=1/(t^2+1)
#We want to compute the Fourier transform g(w)

#Discretize time t
t0=-100.
dt=0.001
t=np.arange(t0,-t0,dt)
#Define function
f=1./(t**2+1.)

#Compute Fourier transform by numpy's FFT function
g=np.fft.fft(f)
#frequency normalization factor is 2*np.pi/dt
w = np.fft.fftfreq(f.size)*2*np.pi/dt

#In order to get a discretisation of the continuous Fourier transform
#we need to multiply g by a phase factor
g*=dt*np.exp(-complex(0,1)*w*t0)/(np.sqrt(2*np.pi))

#Plot Result
pl.scatter(w,g,color="r")
#For comparison we plot the analytical solution
pl.plot(w,np.exp(-np.abs(w))*np.sqrt(np.pi/2),color="g")

pl.gca().set_xlim(-10,10)
pl.show()
pl.close()
```
The resulting plot shows that the script works


Question:
Connecting two points in a 3D scatter plot In the code below, how do I create lines connecting each pair of scatter plots (i.e. linking the green circle to the yellow arrowhead) created by the two lines of code towards the end just before the .show() instruction?
```
import matplotlib.pyplot
from mpl_toolkits.mplot3d import Axes3D

dates       = [20020514, 20020515, 20020516, 20020517, 20020520]
highs       = [1135, 1158, 1152, 1158, 1163]
lows        = [1257, 1253, 1259, 1264, 1252]
upperLimits = [1125.0, 1125.0, 1093.75, 1125.0, 1125.0]
lowerLimits = [1250.0, 1250.0, 1156.25, 1250.0, 1250.0]

zaxisvalues0= [0, 0, 0, 0, 0]
zaxisvalues1= [1, 1, 1, 1, 1]
zaxisvalues2= [2, 2, 2, 2, 2]

fig = matplotlib.pyplot.figure()
ax  = fig.add_subplot(111, projection = '3d')

ax.plot(dates, zaxisvalues1, lowerLimits, color = 'b')
ax.plot(dates, zaxisvalues2, upperLimits, color = 'r')

ax.scatter(dates, zaxisvalues0, highs, color = 'g', marker = "o")
ax.scatter(dates, zaxisvalues0, lows, color = 'y', marker = "^")

matplotlib.pyplot.show()
```

Response:
Draw a line segment between those points:
```
import matplotlib.pyplot
from mpl_toolkits.mplot3d import Axes3D

dates       = [20020514, 20020515, 20020516, 20020517, 20020520]
highs       = [1135, 1158, 1152, 1158, 1163]
lows        = [1257, 1253, 1259, 1264, 1252]
upperLimits = [1125.0, 1125.0, 1093.75, 1125.0, 1125.0]
lowerLimits = [1250.0, 1250.0, 1156.25, 1250.0, 1250.0]

zaxisvalues0= [0, 0, 0, 0, 0]
zaxisvalues1= [1, 1, 1, 1, 1]
zaxisvalues2= [2, 2, 2, 2, 2]

fig = matplotlib.pyplot.figure()
ax  = fig.add_subplot(111, projection = '3d')

ax.plot(dates, zaxisvalues1, lowerLimits, color = 'b')
ax.plot(dates, zaxisvalues2, upperLimits, color = 'r')

for i,j,k,h in zip(dates,zaxisvalues0,lows,highs):
    ax.plot([i,i],[j,j],[k,h],color = 'g')

ax.scatter(dates, zaxisvalues0, highs, color = 'g', marker = "o")
ax.scatter(dates, zaxisvalues0, lows, color = 'y', marker = "^")

matplotlib.pyplot.show()
```
Produces:


Question: Matplotlib imshow offset to match axis? I'm plotting a bunch of UTM coordinates using a matplotlib.pyplot.scatter. I also have a background air photo that I know matches the extent of the figure exactly. When I plot my data and set the axis I can display the scatter correctly. If I plot the air photo using imshow it uses the pixel number as the axis location. I need to shift the image (numpy array) to it's correct UTM position. Any ideas? I'm fairly new to matplotlib and numpy. For example: I know that the top left corner of the image (imshow coordinate: 0,0) has the UTM coordinate (269658.4, 538318.2). How do I tell imshow the same thing? I should also say that I investigated Basemap but it doesn't appear to fully support UTM yet. My study area is very small.

Response:
You need to use the extent keyword argument to imshow. As a quick example:
```
import numpy as np
import matplotlib.pyplot as plt

# Random points between 50000 and 51000
x, y = 1000 * np.random.random((2, 10)) + 50000

# A 10x10 "image"...
image = np.arange(100).reshape((10,10))

# In a lot of cases, image data will be "flipped" vertically, so you may need
# use the `origin` kwarg, as well (or just swap the ymin and ymax ordering).
plt.imshow(image, extent=[x.min(), x.max(), y.min(), y.max()])
plt.plot(x, y, 'ro')

plt.show()
```


Question:
How to label and change the scale of Seaborn kdeplot's axes Here's my code
```
import numpy as np
from numpy.random import randn
import pandas as pd
from scipy import stats
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns

fig = sns.kdeplot(treze, shade=True, color=c1,cut =0, clip=(0,2000))
fig = sns.kdeplot(cjjardim, shade=True, color=c2,cut =0, clip=(0,2000))

fig.figure.suptitle("Plot", fontsize = 24)

plt.xlabel('Purchase amount', fontsize=18)
plt.ylabel('Distribution', fontsize=16)
```
, which results in the following plot: I want to do two things: 1) Change the scale of the y-axis by multiplying its values by 10000 and, if it's possible, add a % sign to the numbers. In other words, I want the y-axis values shown in the above plot to be 0%, 5%, 10%, 15%, 20%, 25%, and 30%. 2) Add more values to the x-axis. I'm particularly interested in showing the data in intervals of 200. In other words, I want the x-axis values shown in the plot to be 0, 200, 400, 600,... and so on.

Response:
1) what you are looking for is most probably some combination of get_yticks() and set_yticks:
```
plt.yticks(fig.get_yticks(), fig.get_yticks() * 100)
plt.ylabel('Distribution [%]', fontsize=16)
```
Note: as mwaskom is commenting times 10000 and a % sign is mathematically incorrect. 2) you can specify where you want your ticks via the xticks function. Then you have more ticks and data get easier to read. You do not get more data that way.
```
plt.xticks([0, 200, 400, 600])
plt.xlabel('Purchase amount', fontsize=18)
```
Note: if you wanted to limit the view to your specified x-values you might even have a glimpse at plt.xlim() and reduce the figure to the interesting range.


Question:
in NetworkX cannot save a graph as jpg or png file I have a graph in NetworkX containing some info. After the graph is shown, I want to save it as jpg or png file. I used the matplotlib function savefig but when the image is saved, it does not contain anything. It is just a white image. Here is a sample code I wrote:
```
import networkx as nx
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(12,12))
ax = plt.subplot(111)
ax.set_title('Graph - Shapes', fontsize=10)

G = nx.DiGraph()
G.add_node('shape1', level=1)
G.add_node('shape2', level=2)
G.add_node('shape3', level=2)
G.add_node('shape4', level=3)
G.add_edge('shape1', 'shape2')
G.add_edge('shape1', 'shape3')
G.add_edge('shape3', 'shape4')
pos = nx.spring_layout(G)
nx.draw(G, pos, node_size=1500, node_color='yellow', font_size=8, font_weight='bold')

plt.tight_layout()
plt.show()
plt.savefig("Graph.png", format="PNG")
```
Why is the image saved without anything inside (just white) ? This is the image saved (just blank):

Response:
It's related to plt.show method. Help of show method:
```
def show(*args, **kw):
    """
    Display a figure.

    When running in ipython with its pylab mode, display all
    figures and return to the ipython prompt.

    In non-interactive mode, display all figures and block until
    the figures have been closed; in interactive mode it has no
    effect unless figures were created prior to a change from
    non-interactive to interactive mode (not recommended).  In
    that case it displays the figures but does not block.

    A single experimental keyword argument, *block*, may be
    set to True or False to override the blocking behavior
    described above.
    """
```
When you call plt.show() in your script, it seems something like file object is still open, and plt.savefig method for writing can not read from that stream completely. but there is a block option for plt.show that can change this behavior, so you can use it:
```
plt.show(block=False)
plt.savefig("Graph.png", format="PNG")
```
Or just comment it:
```
# plt.show()
plt.savefig("Graph.png", format="PNG")
```
Or just save befor show it:
```
plt.savefig("Graph.png", format="PNG")
plt.show()
```
Demo: Here


Question:
Top and bottom line on errorbar with python and seaborn I am trying to plot errorbars with python and seaborn but I am not entirely satisfied with how they look. The default seaborn error bars look like this : But I am looking to add the bottom and top lines on the error bars like this (in order to differentiated between the two error bars, it's the default matplotlib style) : How can I do this in seaborn ? Here is the code:
```
import matplotlib.pyplot as plt
import seaborn as sns

fig1 = plt.figure(figsize=(20, 12))

x_values = [1,2,3,4]
y_values = [1,2,3,4]

y_error = [1,0.5,0.75,0.25]

plt.errorbar(x_values, y_values,  yerr=y_error ,fmt='o', markersize=8)

plt.show()
```

Response:
The capsize parameter should be enough, but for some reason You have to specify the cap.set_markeredgewidth for them to show up too.. Based on: Matplotlib Errorbar Caps Missing.
```
(_, caps, _) = plt.errorbar(
    x_values, y_values, yerr=y_error, fmt='o', markersize=8, capsize=20)

for cap in caps:
    cap.set_markeredgewidth(1)
```
returns: