Question:
How do I set matplotlib plot to "no fill"? I'd like to superimpose one plot over another (they are polygons, really in some lat/lon space, using geopandas, but the plot is simply derived from matplotlib) I have:
```
figZ, axZ = plt.subplots(1, figsize=(11,8.5))
Sfig = X.plot(ax=axZ, color='white', edgecolor='black', lw=0.7)
Y.plot(ax=axZ, color='white', edgecolor='black', lw=0.7, alpha=0.3)
```
How do I set Sfig's color to "no-fill" instead of white? The way it is now it "blurs" my Sfig image (X.plot) by the alpha of the Y.plot one. How do I set "color" to actually transparent?

Response:
I don't expect upvotes, but this is what I found as solution. I'll vote up better ones if they exist:
```
Sfig = X.plot(ax=axZ, facecolor="none",
              edgecolor='black', lw=0.7)
```


Question: warning about too many open figures In a script where I create many figures with fix, ax = plt.subplots(...), I get the warning RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (matplotlib.pyplot.figure) are retained until explicitly closed and may consume too much memory. However, I don't understand why I get this warning, because after saving the figure with fig.savefig(...), I delete it with fig.clear(); del fig. At no point in my code, I have more than one figure open at a time. Still, I get the warning about too many open figures. What does that mean / how can I avoid getting the warning?

Response:
Use .clf or .cla on your figure object instead of creating a new figure. From @DavidZwicker Assuming you have imported pyplot as
```
import matplotlib.pyplot as plt
```
plt.cla() clears an axis, i.e. the currently active axis in the current figure. It leaves the other axes untouched. plt.clf() clears the entire current figure with all its axes, but leaves the window opened, such that it may be reused for other plots. plt.close() closes a window, which will be the current window, if not specified otherwise. plt.close('all') will close all open figures. The reason that del fig does not work is that the pyplot state-machine keeps a reference to the figure around (as it must if it is going to know what the 'current figure' is). This means that even if you delete your ref to the figure, there is at least one live ref, hence it will never be garbage collected. Since I'm polling on the collective wisdom here for this answer, @JoeKington mentions in the comments that plt.close(fig) will remove a specific figure instance from the pylab state machine (plt._pylab_helpers.Gcf) and allow it to be garbage collected.


Question: How can I create stacked line graph? I would like to be able to produce a stacked line graph (similar to the method used here) with Python (preferably using matplotlib, but another library would be fine too). How can I do this? This similar to the stacked bar graph example on their website, except I'd like the top of bar to be connected with a line segment and the area underneath to be filled. I might be able to approximate this by decreasing the gaps between bars and using lots of bars (but this seems like a hack, and besides I'm not sure if it is possible).

Response:
Newer versions of matplotlib contain the function plt.stackplot(), which allows for several different "out-of-the-box" stacked area plots:
```
import numpy as np
import pylab as plt

X = np.arange(0, 10, 1)
Y = X + 5 * np.random.random((5, X.size))

baseline = ["zero", "sym", "wiggle", "weighted_wiggle"]
for n, v in enumerate(baseline):
    plt.subplot(2 ,2, n + 1)
    plt.stackplot(X, *Y, baseline=v)
    plt.title(v)
    plt.axis('tight')
plt.show()
```


Question: How to show minor tick labels on log-scale with Matplotlib Does anyone know how to show the labels of the minor ticks on a logarithmic scale with Python/Matplotlib?

Response:
You can use plt.tick_params(axis='y', which='minor') to set the minor ticks on and format them with the matplotlib.ticker FormatStrFormatter. For example,
```
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
x = np.linspace(0,4,1000)
y = np.exp(x)
plt.plot(x, y)
ax = plt.gca()
ax.set_yscale('log')
plt.tick_params(axis='y', which='minor')
ax.yaxis.set_minor_formatter(FormatStrFormatter("%.1f"))
plt.show()
```


Question:
How do I add a title and axis labels to Seaborn Heatmap? I want to add a title to a seaborn heatmap. Using Pandas and iPython Notebook code is below,
```
a1_p = a1.pivot_table( index='Postcode', columns='Property Type', values='Count', aggfunc=np.mean, fill_value=0)

sns.heatmap(a1_p, cmap="YlGnBu")
```
the data is pretty straight forward:
```

```python
a1_p
#Output
#Property Type   Flat    Terraced house  Unknown
#Postcode
#E1  11  0   0
#E14 12  0   0
#E1W 6   0   0
#E2  6   0   0
#```
```

Response:
heatmap is an axes-level function, so you should be able to use just plt.title or ax.set_title:
```
%matplotlib inline
import numpy as np
import os
import seaborn as sns
import matplotlib.pyplot as plt

data = np.random.randn(10,12)

ax = plt.axes()
sns.heatmap(data, ax = ax)

ax.set_title('lalala')
plt.show()
```


Question:
How to remove frame from a figure To remove frame in figure, I write
```
frameon=False
```
works perfect with pyplot.figure, but with matplotlib.Figure it only removes the gray background, the frame stays. Also, I only want the lines to show, and all the rest of figure be transparent. with pyplot I can do what I want, I want to do it with matplotlib for some long reason I'd rather not mention to extend my question.

Response:
ax.axis('off'), will as Joe Kington pointed out, remove everything except the plotted line. For those wanting to only remove the frame (border), and keep labels, tickers etc, one can do that by accessing the spines object on the axis. Given an axis object ax, the following should remove borders on all four sides:
```
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
```
And, in case of removing x and y ticks from the plot:
```
ax.get_xaxis().set_ticks([])
 ax.get_yaxis().set_ticks([])
```


Question: Matplotlib: Scatter Plot to Foreground on top of a Contour Plot Does anyone know a way to bring a scatter plot to the foreground in matplotlib? I have to display the scatter plotting on top of the contour, but by default it is plotted underneath...

Response:
You can manually choose in which order the different plots are to be displayed with the zorder parameter of e.g. the scatter method. To demonstrate, see the code below, where the scatter plot in the left subplot has zorder=1 and in the right subplot it has zorder=-1. The object with the highest zorder is placed on top. This means that the scatter will be placed on top of the contour in the first subplot, while it is placed underneath in the second subplot.
```
import numpy as np
import matplotlib.cm as cm
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = 10.0 * (Z2 - Z1)

norm = cm.colors.Normalize(vmax=abs(Z).max(), vmin=-abs(Z).max())
cmap = cm.PRGn

levels = np.arange(-2.0, 1.601, 0.4)

fig, axes = plt.subplots(1,2, sharey=True)

for ax, zord in zip(axes, [1, -1]):
    ax.contourf(X, Y, Z, levels,
                cmap=cm.get_cmap(cmap, len(levels)-1),
                norm=norm)
    ax.autoscale(False) # To avoid that the scatter changes limits
    ax.scatter(np.random.uniform(-3,3,10),
               np.random.uniform(-2,2,10),
               zorder=zord)
    ax.set_title('Scatter with zorder={0}'.format(zord))
```


Question:
How to read image file from S3 bucket directly into memory? I have the following code
```
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import boto3
s3 = boto3.resource('s3', region_name='us-east-2')
bucket = s3.Bucket('sentinel-s2-l1c')
object = bucket.Object('tiles/10/S/DG/2015/12/7/0/B01.jp2')
object.download_file('B01.jp2')
img=mpimg.imread('B01.jp2')
imgplot = plt.imshow(img)
plt.show(imgplot)
```
and it works. But the problem it downloads file into current directory first. Is it possible to read file and decode it as image directly in RAM?

Response:
I would suggest using io module to read the file directly in to memory, without having to use a temporary file at all. For example:
```
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import boto3
import io

s3 = boto3.resource('s3', region_name='us-east-2')
bucket = s3.Bucket('sentinel-s2-l1c')
object = bucket.Object('tiles/10/S/DG/2015/12/7/0/B01.jp2')

file_stream = io.StringIO()
object.download_fileobj(file_stream)
img = mpimg.imread(file_stream)
# whatever you need to do
```
You could also use io.BytesIO if your data is binary.


Question: Putting text in top left corner of matplotlib plot How can I put text in the top left (or top right) corner of a matplotlib figure, e.g. where a top left legend would be, or on top of the plot but in the top left corner? E.g. if it's a plt.scatter(), then something that would be within the square of the scatter, put in the top left most corner. I'd like to do this without ideally knowing the scale of the scatterplot being plotted for example, since it will change from dataset to data set. I just want it the text to be roughly in the upper left, or roughly in the upper right. With legend type positioning it should not overlap with any scatter plot points anyway.

Response:
You can use text.
```
plt.text(x, y, s, fontsize=12)
```
text coordinates can be given relative to the axis, so the position of your text will be independent of the size of the plot: The default transform specifies that text is in data coords, alternatively, you can specify text in axis coords (0,0 is lower-left and 1,1 is upper-right). The example below places text in the center of the axes::
```
plt.text(0.5, 0.5, 'matplotlib',
     horizontalalignment='center',
     verticalalignment='center',
     transform = ax.transAxes)
```
To prevent the text to interfere with any point of your scatter is more difficult afaik. The easier method is to set y_axis (ymax in ylim((ymin,ymax))) to a value a bit higher than the max y-coordinate of your points. In this way you will always have this free space for the text. EDIT: here you have an example:
```py
from matplotlib import pyplot as plt

f, ax = plt.subplots()
plt.scatter([3,5,2,6,8],[5,3,2,1,5])
plt.text(.01, .99, 'matplotlib', ha='left', va='top', transform=ax.transAxes)
f.tight_layout()
```
The ha and va parameters set the alignment of your text relative to the insertion point. ie. ha='left' is a good set to prevent a long text to go out of the left axis when the frame is reduced (made narrower) manually.


Question:
Save multiple plots in a single PDF file plotting module
```
def plotGraph(X,Y):
    fignum = random.randint(0,sys.maxint)
    plt.figure(fignum)
    ### Plotting arrangements ###
    return fignum
```
main module
```
import matplotlib.pyplot as plt
### tempDLStats, tempDLlabels are the argument
plot1 = plotGraph(tempDLstats, tempDLlabels)
plot2 = plotGraph(tempDLstats_1, tempDLlabels_1)
plot3 = plotGraph(tempDLstats_2, tempDLlabels_2)
plt.show()
```
I want to save all the graphs plot1, plot2, plot3 to a single PDF file. Is there any way to achieve it? I can't include the plotGraph function in the main module. There's a function named pyplot.savefig but that seems to work only with a single figure. Is there any other way to accomplish it?

Response:
If someone ends up here from google, looking to convert a single figure to a .pdf (that was what I was looking for):
```
import matplotlib.pyplot as plt

f = plt.figure()
plt.plot(range(10), range(10), "o")
plt.show()

f.savefig("foo.pdf", bbox_inches='tight')
```


Question:
Matplotlib savefig with a legend outside the plot Reading the following article, I managed to put a legend outside plot. How to put the legend out of the plot code:
```
import matplotlib.pyplot as pyplot

x = [0, 1, 2, 3, 4]
y = [xx*xx for xx in x]

fig = pyplot.figure()
ax  = fig.add_subplot(111)

box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width*0.8, box.height])

ax.plot(x, y)
leg = ax.legend(['abc'], loc = 'center left', bbox_to_anchor = (1.0, 0.5))
#pyplot.show()

fig.savefig('aaa.png', bbox_inches='tight')
```
pyplot.show() displays the correct plot with a legend outside it. But when I save it as a file with fig.savefig(), the legend is truncated. Some googling shows me workarounds such as adding bbox_extra_artists=[leg.legendPatch] or bbox_extra_artists=[leg] to savefig(), but neither worked. What is the correct way to do it? Matplotlib version is 0.99.3. Thanks.

Response:
The problem is that when you plot dynamically, matplotlib determines the borders automatically to fit all your objects. When you save a file, things are not being done automatically, so you need to specify the size of your figure, and then the bounding box of your axes object. Here is how to correct your code:
```
import matplotlib.pyplot as pyplot

x = [0, 1, 2, 3, 4]
y = [xx*xx for xx in x]

fig = pyplot.figure(figsize=(3,3))
ax  = fig.add_subplot(111)

#box = ax.get_position()
#ax.set_position([0.3, 0.4, box.width*0.3, box.height])
# you can set the position manually, with setting left,buttom, witdh, hight of the axis
# object
ax.set_position([0.1,0.1,0.5,0.8])
ax.plot(x, y)
leg = ax.legend(['abc'], loc = 'center left', bbox_to_anchor = (1.0, 0.5))

fig.savefig('aaa.png')
```


Question:
Why is my plt.savefig is not working? I have a simple python code as follows:
```
import numpy as np
import matplotlib.pyplot as plt

"""
Here are the solutions and the plot.
"""

# Create the axis and plot.
plt.axis([0, 10, 0, 10])
axis_x = range(1, 11)
grd = [1.1, 2.1, 3.1, 4.1, 5.1, 6.1, 7.1, 8.1, 9.1, 10.1]
grd2 = [1.2, 2.2, 3.2, 4.2, 5.2, 6.2, 7.2, 8.2, 9.2, 10.2]
plt.plot(axis_x, grd, '-g', label='BR1')
plt.plot(axis_x, grd2, '-b', label='BR2')
plt.legend(loc='upper left')
plt.grid()
plt.show()

# Save the results vector to a text file.
np.savetxt('test.out', (grd, grd2))

# Save the figure as '.eps' file.
plt.savefig('expl.pdf', format='pdf', dpi=1200)
```
When I open the output files expl.pdf and/or test.out I find them blank and nothing in there. Why? Thanks.

Response: When you close the image displayed by plt.show(), the image is closed and freed from memory. You should call savefig and savetxt before calling show.


Question:
How do I set color to Rectangle in Matplotlib? How do I set color to Rectangle for example in matplotlib? I tried using argument color, but had no success. I have following code:
```
fig=pylab.figure()
ax=fig.add_subplot(111)

pylab.xlim([-400, 400])
pylab.ylim([-400, 400])
patches = []
polygon = Rectangle((-400, -400), 10, 10, color='y')
patches.append(polygon)

p = PatchCollection(patches, cmap=matplotlib.cm.jet)
ax.add_collection(p)
ax.xaxis.set_major_locator(MultipleLocator(20))
ax.yaxis.set_major_locator(MultipleLocator(20))

pylab.show()
```

Response:
I couldn't get your code to work, but hopefully this will help:
```
import matplotlib
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
rect1 = matplotlib.patches.Rectangle((-200,-100), 400, 200, color='yellow')
rect2 = matplotlib.patches.Rectangle((0,150), 300, 20, color='red')
rect3 = matplotlib.patches.Rectangle((-300,-50), 40, 200, color='#0099FF')
circle1 = matplotlib.patches.Circle((-200,-250), radius=90, color='#EB70AA')
ax.add_patch(rect1)
ax.add_patch(rect2)
ax.add_patch(rect3)
ax.add_patch(circle1)
plt.xlim([-400, 400])
plt.ylim([-400, 400])
plt.show()
```
produces:


Question:
Seaborn plots not showing up I'm sure I'm forgetting something very simple, but I cannot get certain plots to work with Seaborn. If I do:
```
import seaborn as sns
```
Then any plots that I create as usual with matplotlib get the Seaborn styling (with the grey grid in the background). However, if I try to do one of the examples, such as:
```

```python
import seaborn as sns
```

```python
sns.set()
```

```python
df = sns.load_dataset('iris')
```

```python
sns.pairplot(df, hue='species', size=2.5)
#Output
#<seaborn.axisgrid.PairGrid at 0x3e59150>
#```
#The pairplot function returns a PairGrid object, but the plot doesn't show up. I'm a little confused because matplotlib seems to be functioning properly, and the Seaborn styles are applied to other matplotlib plots, but the Seaborn functions don't seem to do anything. Does anybody have any idea what might be the problem?
```

Response:
Plots created using seaborn need to be displayed like ordinary matplotlib plots. This can be done using the
```
plt.show()
```
function from matplotlib. Originally I posted the solution to use the already imported matplotlib object from seaborn (sns.plt.show()) however this is considered to be a bad practice. Therefore, simply directly import the _matplotlib.pyplot_ module and show your plots with
```
import matplotlib.pyplot as plt
plt.show()
```
If the IPython notebook is used the inline backend can be invoked to remove the necessity of calling show after each plot. The respective magic is
```
%matplotlib inline
```


Question: matplotlib -- interactively select points or locations? In R, there is a function locator which is like Matlab's ginput where you can click on the figure with a mouse and select any x,y coordinate. In addition, there is a function called identify(x,y) where if you give it a set of points x,y that you have plotted and then click on the figure, it will return the index of the x,y point which lies nearest (within an adjustable tolerance) to the location you have selected (or multiple indices, if multiple points are selected). Is there such a functionality in Matplotlib?

Response:
You may want to use a pick event :
```
fig = figure()
ax1 = fig.add_subplot(111)
ax1.set_title('custom picker for line data')
line, = ax1.plot(rand(100), rand(100), 'o', picker=line_picker)
fig.canvas.mpl_connect('pick_event', onpick2)
```
Tolerance set by picker parameter there:
```
line, = ax1.plot(rand(100), 'o', picker=5)  # 5 points tolerance
```


Question: Reverse colormap in matplotlib I would like to know how to simply reverse the color order of a given colormap in order to use it with plot_surface.

Response: The standard colormaps also all have reversed versions. They have the same names with _r tacked on to the end. (Documentation here.)


Question:
Using %matplotlib notebook after %matplotlib inline in Jupyter Notebook doesn't work I am using Jupyter Notebook for plotting piechart figures. In first cell with my code I have a magic command %matplotlib inline and after this magic command I run my code, everything works fine and my figure renders. But in second cell when I set %matplotlib notebook for interactive plotting my figure won't render after running this second cell. I need to restart kernel and run cell with %matplotlib notebook again and cannot run %matplotlib inline command before that. Here is my code for first cell with %matplotlib inline, which renders fine:
```
import matplotlib.pyplot as plt

%matplotlib inline

labels = "No", "Yes"
sizes = [100, 50]

fig, ax = plt.subplots(figsize=(6, 6))

_, texts, autotexts = ax.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%',
             shadow=False, startangle=90)

ax.axis('equal')
```
After that I have second cell with same code, just %matplotlib inline is changed to %matplotlib notebook. Figure won't render after I run this cell and I need to restart kernel and run this cell again. Why?

Response:
You just have the wrong order of your commands. A backend should be set before importing pyplot in jupyter. Or in other words, after changing the backend, pyplot needs to be imported again. Therefore call %matplotlib ... prior to importing pyplot. In first cell:
```
%matplotlib inline
import matplotlib.pyplot as plt
plt.plot([1,1.6,3])
```
In second cell:
```
%matplotlib notebook
#calling it a second time may prevent some graphics errors
%matplotlib notebook
import matplotlib.pyplot as plt
plt.plot([1,1.6,3])
```


Question: How to plot normal distribution Given a mean and a variance is there a simple function call which will plot a normal distribution?

Response:
```
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
import math

mu = 0
variance = 1
sigma = math.sqrt(variance)
x = np.linspace(mu - 3*sigma, mu + 3*sigma, 100)
plt.plot(x, stats.norm.pdf(x, mu, sigma))
plt.show()
```


Question:
Plotting lines connecting points I know there is another very similar question, but I could not extract the information I need from it. plotting lines in pairs I have 4 points in the (x,y) plane: x=[x1,x2,x3,x4] and y=[y1,y2,y3,y4]
```
x=[-1 ,0.5 ,1,-0.5]
y=[ 0.5,  1, -0.5, -1]
```
Now, I can plot the four points by doing:
```
import matplotlib.pyplot as plt

plt.plot(x,y, 'ro')
plt.axis('equal')
plt.show()
```
But, apart from the four points, I would like to have 2 lines: 1) one connecting (x1,y1) with (x2,y2) and 2) the second one connecting (x3,y3) with (x4,y4). This is a simple toy example. In the real case I have 2N points in the plane. How can I get the desired output: for points with two connecting lines ? Thank you.

Response:
I think you're going to need separate lines for each segment:
```
import numpy as np
import matplotlib.pyplot as plt

x, y = np.random.random(size=(2,10))

for i in range(0, len(x), 2):
    plt.plot(x[i:i+2], y[i:i+2], 'ro-')

plt.show()
```
(The numpy import is just to set up some random 2x10 sample data)


Question:
How to dynamically update a plot in a loop in IPython notebook (within one cell) Environment: Python 2.7, Matplotlib 1.3, IPython notebook 1.1, Linux, and Chrome. The code is in one single input cell, using --pylab=inline. I want to use IPython notebook and Pandas to consume a stream and dynamically update a plot every five seconds. When I just use a print statement to print the data in text format, it works perfectly fine: the output cell just keeps printing data and adding new rows. But when I try to plot the data (and then update it in a loop), the plot never shows up in the output cell. But if I remove the loop, and just plot it once, it works fine. Then I did some simple test:
```
i = pd.date_range('2013-1-1',periods=100,freq='s')
while True:
    plot(pd.Series(data=np.random.randn(100), index=i))
    #pd.Series(data=np.random.randn(100), index=i).plot() also tried this one
    time.sleep(5)
```
The output will not show anything until I manually interrupt the process (Ctrl + M + I). And after I interrupt it, the plot shows correctly as multiple overlapped lines. But what I really want is a plot that shows up and gets updated every five seconds (or whenever the plot() function gets called, just like what print statement outputs I mentioned above, which works well). Only showing the final chart after the cell is completely done is not what I want. I even tried to explicitly add the draw() function after each plot(), etc. None of them works. How can I dynamically update a plot by a for/while loop within one cell in IPython notebook?

Response:
Use the IPython.display module:
```
%matplotlib inline
import time
import pylab as pl
from IPython import display
for i in range(10):
    pl.plot(pl.randn(100))
    display.clear_output(wait=True)
    display.display(pl.gcf())
    time.sleep(1.0)
```


Question: Plot mean and standard deviation I have several values of a function at different x points. I want to plot the mean and std in python, like the answer of this SO question. I know this must be easy using matplotlib, but I have no idea of the function's name that can do that. Does anyone know it?

Response:
plt.errorbar can be used to plot x, y, error data (as opposed to the usual plt.plot)
```
import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 2, 3, 4, 5])
y = np.power(x, 2) # Effectively y = x**2
e = np.array([1.5, 2.6, 3.7, 4.6, 5.5])

plt.errorbar(x, y, e, linestyle='None', marker='^')

plt.show()
```
plt.errorbar accepts the same arguments as plt.plot with additional yerr and xerr which default to None (i.e. if you leave them blank it will act as plt.plot).


Question:
Matplotlib remove patches from figure In my case, I want to remove one of the circle when clicking reset button. However, ax.clear() would clear all circles on the current figure. Can someone tell me how to remove only part of the patches?
```
import matplotlib.patches as patches
import matplotlib.pyplot as plt
from matplotlib.widgets import Button

fig = plt.figure()
ax = fig.add_subplot(111)

circle1 = patches.Circle((0.3, 0.3), 0.03, fc='r', alpha=0.5)
circle2 = patches.Circle((0.4, 0.3), 0.03, fc='r', alpha=0.5)
button = Button(plt.axes([0.8, 0.025, 0.1, 0.04]), 'Reset', color='g', hovercolor='0.975')
ax.add_patch(circle1)
ax.add_patch(circle2)

def reset(event):
    '''what to do here'''
    ax.clear()

button.on_clicked(reset)
plt.show()
```

Response:
Try this:
```
def reset(event):
    circle1.remove()
```
Also maybe you prefer:
```
def reset(event):
    circle1.set_visible(False)
```


Question:
pandas pie chart plot remove the label text on the wedge the pie chart example on pandas plotting tutorial http://pandas.pydata.org/pandas-docs/version/0.15.0/visualization.html generates the following figure: with this code:
```
import matplotlib.pyplot as plt
plt.style.use('ggplot')
import numpy as np
np.random.seed(123456)

import pandas as pd
df = pd.DataFrame(3 * np.random.rand(4, 2), index=['a', 'b', 'c', 'd'], columns=['x', 'y'])

f, axes = plt.subplots(1,2, figsize=(10,5))
for ax, col in zip(axes, df.columns):
    df[col].plot(kind='pie', autopct='%.2f', labels=df.index,  ax=ax, title=col, fontsize=10)
    ax.legend(loc=3)

plt.show()
```
I want to remove the text label (a,b,c,d) from both subplots, because for my application those label are long, so I only want to show them in legend. After read this: How to add a legend to matplotlib pie chart?, I figure out an way with matplotlib.pyplot.pie but the figure is not as fancy even if i am still using ggplot.
```
f, axes = plt.subplots(1,2, figsize=(10,5))
for ax, col in zip(axes, df.columns):
    patches, text, _ = ax.pie(df[col].values, autopct='%.2f')
    ax.legend(patches, labels=df.index, loc='best')
```
My question is, is there a way that can combine the things I want from both side? to be clear, I want the fanciness from pandas, but remove the text from the wedges. Thank you

Response:
You can turn off the labels in the chart, and then define them within the call to legend:
```
df[col].plot(kind='pie', autopct='%.2f', labels=['','','',''],  ax=ax, title=col, fontsize=10)
ax.legend(loc=3, labels=df.index)
```
or
```
... labels=None ...
```


Question: How to create a heat map in python that ranges from green to red? I'm trying to plot log ratios from the range -3 to 3 and want negative ratios to be green and positive to be red, with a log ratio of 0 (center) to be white in color. None of the pre-existing color schemes in matplotlib provide this option, and I haven't been able to figure out how to output a nice gradient manually.

Response:
Using matplotlib.colors.LinearSegmentedColormap's from_list method seems more intuitive than some of the other answers here.
```
from  matplotlib.colors import LinearSegmentedColormap
cmap=LinearSegmentedColormap.from_list('rg',["r", "w", "g"], N=256)
```
Or for more sophisticated tuning:
```
from  matplotlib.colors import LinearSegmentedColormap
c = ["darkred","red","lightcoral","white", "palegreen","green","darkgreen"]
v = [0,.15,.4,.5,0.6,.9,1.]
l = list(zip(v,c))
cmap=LinearSegmentedColormap.from_list('rg',l, N=256)
```


Question: cumulative distribution plots python I am doing a project using python where I have two arrays of data. Let's call them pc and pnc. I am required to plot a cumulative distribution of both of these on the same graph. For pc it is supposed to be a less than plot i.e. at (x,y), y points in pc must have value less than x. For pnc it is to be a more than plot i.e. at (x,y), y points in pnc must have value more than x. I have tried using histogram function - pyplot.hist. Is there a better and easier way to do what i want? Also, it has to be plotted on a logarithmic scale on the x-axis.

Response:
You were close. You should not use plt.hist as numpy.histogram, that gives you both the values and the bins, than you can plot the cumulative with ease:
```
import numpy as np
import matplotlib.pyplot as plt

# some fake data
data = np.random.randn(1000)
# evaluate the histogram
values, base = np.histogram(data, bins=40)
#evaluate the cumulative
cumulative = np.cumsum(values)
# plot the cumulative function
plt.plot(base[:-1], cumulative, c='blue')
#plot the survival function
plt.plot(base[:-1], len(data)-cumulative, c='green')

plt.show()
```


Question: Matplotlib coord. sys origin to top left How can I flip the origin of a matplotlib plot to be in the upper-left corner - as opposed to the default lower-left? I'm using matplotlib.pylab.plot to produce the plot (though if there is another plotting routine that is more flexible, please let me know). I'm looking for the equivalent of the matlab command: axis ij; Also, I've spent a couple hours surfing matplotlib help and google but haven't come up with an answer. Some info on where I could have looked up the answer would be helpful as well.

Response:
The easiest way is to use:
```
plt.gca().invert_yaxis()
```
After you plotted the image. Origin works only for imshow.


Question:
Matplotlib vline label parameter not showing I want to label my vertical lines with matplotlib's .vline command, but for some reason the label parameter doesn't do anything/show anything on the final plot. Does anyone know how to get the label to show?
```
plt.vlines(x=pah, ymin=0, ymax=0.6, colors='0.75', linestyles='dashed', label='PAHs')
```
Everything works apart from the label. Many thanks, L

Response:
The label keyword is displayed in the legend. You need create the legend explicitly to see the label in the plot:
```
plt.vlines([1,2,3], 0, 1, label='test')
plt.legend()
```


Question:
Keep plotting window open in Matplotlib When writing scripts that use matplotlib, I temporally get an interactive graphing window when I run the script, which immediately goes away before I can view the plot. If I execute the same code interactively inside iPython, the graphing window stays open. How can I get matplotlib to keep a plot open once it is produces a graph when I run a script? For example, I can save this plot, but I cannot display it with show():
```
from matplotlib import pyplot as plt
import scipy as sp

x =  sp.arange(10)
y =  sp.arange(10)

plt.plot(x,y)
plt.show()
```

Response: According to the documentation, there's an experimental block parameter you can pass to plt.show(). Of course, if your version of matplotlib isn't new enough, it won't have this. If you have this feature, you should be able to replace plt.show() with plt.show(block=True) to get your desired behavior.


Question:
How do I plot Shapely polygons and objects using Matplotlib? I want to use Shapely for my computational geometry project. I need to be able to visualize and display polygons, lines, and other geometric objects for this. I've tried to use Matplotlib for this but I am having trouble with it.
```py
from shapely.geometry import Polygon
import matplotlib.pyplot as plt

polygon1 = Polygon([(0,5),
                    (1,1),
                    (3,0),
                    ])

plt.plot(polygon1)
plt.show()
```
I would like to be able to display this polygon in a plot. How would I change my code to do this?

Response:
Use:
```
import matplotlib.pyplot as plt

x,y = polygon1.exterior.xy
plt.plot(x,y)
```
Or, more succinctly:
```
plt.plot(*polygon1.exterior.xy)
```


Question:
How to plot gamma distribution with alpha and beta parameters in python I want to plot a gamma distribution with alpha = 29 (the scale) and beta = 3 (the size). In other words, I want to plot the pdf for Gamma(29,3). How do I do this if according to the documentation, the python gamma function only has parameters a and x and the size parameter doesn't exist? I thought loc was beta, but I think it's actually offset, so the code below is wrong...
```
import numpy as np
import scipy.stats as stats
from matplotlib import pyplot as plt

x = np.linspace (0, 100, 200)
y1 = stats.gamma.pdf(x, a=29, loc=3) #a is alpha, loc is beta???
plt.plot(x, y1, "y-", label=(r'$\alpha=29, \beta=3$'))

plt.ylim([0,0.08])
plt.xlim([0,150])
plt.show()
```

Response:
According to the documentation, you want to use the scale parameter (theta), but since you are defining beta, which is the inverse of theta, then you pass scale with the value of 1/beta, which in your example would be 1/3 or 0.33333. Therefore, try:
```
y1 = stats.gamma.pdf(x, a=29, scale=0.33333)
```


Question: matplotlib bar graph black - how do I remove bar borders I'm using pyplot.bar but I'm plotting so many points that the color of the bars is always black. This is because the borders of the bars are black and there are so many of them that they are all squished together so that all you see is the borders (black). Is there a way to remove the bar borders so that I can see the intended color?

Response: Set the edgecolor to "none": bar(..., edgecolor = "none")


Question:
How to create a density plot In R I can create the desired output by doing:
```
data = c(rep(1.5, 7), rep(2.5, 2), rep(3.5, 8),
         rep(4.5, 3), rep(5.5, 1), rep(6.5, 8))
plot(density(data, bw=0.5))
```
In python (with matplotlib) the closest I got was with a simple histogram:
```
import matplotlib.pyplot as plt
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
plt.hist(data, bins=6)
plt.show()
```
I also tried the normed=True parameter but couldn't get anything other than trying to fit a gaussian to the histogram. My latest attempts were around scipy.stats and gaussian_kde, following examples on the web, but I've been unsuccessful so far.

Response:
Five years later, when I Google "how to create a kernel density plot using python", this thread still shows up at the top! Today, a much easier way to do this is to use seaborn, a package that provides many convenient plotting functions and good style management.
```
import numpy as np
import seaborn as sns
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
sns.set_style('whitegrid')
sns.kdeplot(np.array(data), bw=0.5)
```


Question: matplotlib - increase resolution to see details I have a big process that is composed of tasks (about 600), and I created a figure to watch the order they are launched with and the time they take. To do this, I used matplotlib and a barh. The figure is ok (my 1st matplotlib success !), but: I would like to see the details and zoom on the picture when exported (as PNG, for instance), as the zoom option allows when matplotlib displays the result with the show() command the legends of the Y axis are too close and unreadable I tried to increase the resolution as said in this other SO post, this is better but details are not precise enough. Here are my results so far: full result zoom with matplotlib Do you know how I could improve readability ? Thanks a lot (else, all my efforts would be useless, I'm afraid...) PS: I'm using matplotlib 1.1.1 and python 2.7.

Response:
I managed to do so, on Evert's advice, by using a very big resolution with a very small font. Here are the most important steps:
```
import pylab as pl
pl.figure(figsize=(70, 70)) # This increases resolution
pl.savefig('test.eps', format='eps', dpi=900) # This does, too
pl.annotate(..., fontsize='xx-small', ...)
```


Question:
vertical & horizontal lines in matplotlib I do not quite understand why I am unable to create horizontal and vertical lines at specified limits. I would like to bound the data by this box. However, the sides do not seem to comply with my instructions. Why is this?
```
# CREATING A BOUNDING BOX
# BOTTOM HORIZONTAL
plt.axhline(y=.4, xmin=0.25, xmax=0.402, linewidth=2, color = 'k')
# RIGHT VERTICAL
plt.axvline(x=0.402, ymin=0.4, ymax = 0.615, linewidth=2, color='k')
# LEFT VERTICAL
plt.axvline(x=0.1, ymin=0.58, ymax = 0.79, linewidth=2, color='k')
plt.show()
```

Response: The pyplot functions you are calling, axhline() and axvline() draw lines that span a portion of the axis range, regardless of coordinates. The parameters xmin or ymin use value 0.0 as the minimum of the axis and 1.0 as the maximum of the axis. Instead, use plt.plot((x1, x2), (y1, y2), 'k-') to draw a line from the point (x1, y1) to the point (x2, y2) in color k. See pyplot.plot.


Question:
Get data points from Seaborn distplot I use
```
sns.distplot
```
to plot a univariate distribution of observations. Still, I need not only the chart, but also the data points. How do I get the data points from matplotlib Axes (returned by distplot)?

Response:
You can use the matplotlib.patches API. For instance, to get the first line:
```
sns.distplot(x).get_lines()[0].get_data()
```
This returns two numpy arrays containing the x and y values for the line. For the bars, information is stored in:
```
sns.distplot(x).patches
```
You can access the bar's height via the function patches.get_height():
```
[h.get_height() for h in sns.distplot(x).patches]
```


Question:
How to remove gaps between bars in a bar chart I'm making a bar chart in Matplotlib with a call like this:
```
xs.bar(bar_lefts, bar_heights, facecolor='black', edgecolor='black')
```
I get a barchart that looks like this: What I'd like is one with no white gap between consecutive bars, e.g. more like this: Is there a way to achieve this in Matplotlib using the bar() function?

Response: Add width=1.0 as a keyword argument to bar(). E.g. xs.bar(bar_lefts, bar_heights, width=1.0, facecolor='black', edgecolor='black'). This will fill the bars gaps vertically.


Question:
adding extra axis ticks using matplotlib I have a simple plot code as
```
plt.plot(x,y)
plt.show()
```
I want to add some extra ticks on the x-axis in addition to the current ones, let's say at
```
extraticks=[2.1, 3, 7.6]
```
As you see I do not have a pattern for ticks so I do not want to increase the tick frequency for the whole axis; just keep the original ones and add those extras... Is it possible, at all? Regards

Response:
Yes, you can try something like:
```
plt.xticks(list(plt.xticks()[0]) + extraticks)
```
The function to use is xticks(). When called without arguments, it returns the current ticks. Calling it with arguments, you can set the tick positions and, optionally, labels.


Question: Is it possible to add a string as a legend item I am producing some plots in matplotlib and would like to add explanatory text for some of the data. I want to have a string inside my legend as a separate legend item above the '0-10' item. Does anyone know if there is a possible way to do this? This is the code for my legend: ax.legend(['0-10','10-100','100-500','500+'],loc='best')

Response:
Alternative solution, kind of dirty but pretty quick.
```
import pylab as plt

X = range(50)
Y = range(50)
plt.plot(X, Y, label="Very straight line")

# Create empty plot with blank marker containing the extra label
plt.plot([], [], ' ', label="Extra label on the legend")

plt.legend()
plt.show()
```


Question:
How to skip empty dates (weekends) in a financial plot
```
ax.plot_date((dates, dates), (highs, lows), '-')
```
I'm currently using this command to plot financial highs and lows using Matplotlib. It works great, but how do I remove the blank spaces in the x-axis left by days without market data, such as weekends and holidays? I have lists of dates, highs, lows, closes and opens. I can't find any examples of creating a graph with an x-axis that show dates but doesn't enforce a constant scale.

Response:
Up to date answer (2018) with Matplotlib 2.1.2, Python 2.7.12 The function equidate_ax handles everything you need for a simple date x-axis with equidistant spacing of data points. Realised with ticker.FuncFormatter based on this example.
```
from __future__ import division
from matplotlib import pyplot as plt
from matplotlib.ticker import FuncFormatter
import numpy as np
import datetime

def equidate_ax(fig, ax, dates, fmt="%Y-%m-%d", label="Date"):
    """
    Sets all relevant parameters for an equidistant date-x-axis.
    Tick Locators are not affected (set automatically)

    Args:
        fig: pyplot.figure instance
        ax: pyplot.axis instance (target axis)
        dates: iterable of datetime.date or datetime.datetime instances
        fmt: Display format of dates
        label: x-axis label
    Returns:
        None

    """
    N = len(dates)
    def format_date(index, pos):
        index = np.clip(int(index + 0.5), 0, N - 1)
        return dates[index].strftime(fmt)
    ax.xaxis.set_major_formatter(FuncFormatter(format_date))
    ax.set_xlabel(label)
    fig.autofmt_xdate()

#
# Some test data (with python dates)
#
dates = [datetime.datetime(year, month, day) for year, month, day in [
    (2018,2,1), (2018,2,2), (2018,2,5), (2018,2,6), (2018,2,7), (2018,2,28)
]]
y = np.arange(6)

# Create plots. Left plot is default with a gap
fig, [ax1, ax2] = plt.subplots(1, 2)
ax1.plot(dates, y, 'o-')
ax1.set_title("Default")
ax1.set_xlabel("Date")

# Right plot will show equidistant series
# x-axis must be the indices of your dates-list
x = np.arange(len(dates))
ax2.plot(x, y, 'o-')
ax2.set_title("Equidistant Placement")
equidate_ax(fig, ax2, dates)
```


Question:
Second y-axis label getting cut off I'm trying to plot two sets of data in a bar graph with matplotlib, so I'm using two axes with the twinx() method. However, the second y-axis label gets cut off. I've tried a few different methods with no success (tight_layout(), setting the major_pads in rcParams, etc...). I feel like the solution is simple, but I haven't come across it yet. Here's a MWE:
```
#!/usr/bin/env python
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

matplotlib.rcParams.update({'font.size': 21})
ax = plt.gca()
plt.ylabel('Data1') #Left side
ax2 = ax.twinx()
for i in range(10):
  if(i%2==0):
    ax.bar(i,np.random.randint(10))
  else:
    ax2.bar(i,np.random.randint(1000),color='k')

plt.ylabel('Data2') #Right
```
side plt.savefig("test.png")

Response: I just figured it out: the trick is to use bbox_inches='tight' in savefig. E.G. plt.savefig("test.png",bbox_inches='tight')


Question: Plot a horizontal line on a given plot How do I add a horizontal line to an existing plot?

Response:
Use axhline (a horizontal axis line). For example, this plots a horizontal line at y = 0.5:
```
import matplotlib.pyplot as plt
plt.axhline(y=0.5, color='r', linestyle='-')
plt.show()
```


Question:
Specify format of floats for tick labels I am trying to set the format to two decimal numbers in a matplotlib subplot environment. Unfortunately, I do not have any idea how to solve this task. To prevent using scientific notation on the y-axis I used ScalarFormatter(useOffset=False) as you can see in my snippet below. I think my task should be solved by passing further options/arguments to the used formatter. However, I could not find any hint in matplotlib's documentation. How can I set two decimal digits or none (both cases are needed)? I am not able to provide sample data, unfortunately. -- SNIPPET --
```
f, axarr = plt.subplots(3, sharex=True)

data = conv_air
x = range(0, len(data))

axarr[0].scatter(x, data)
axarr[0].set_ylabel('$T_\mathrm{air,2,2}$', size=FONT_SIZE)
axarr[0].yaxis.set_major_locator(MaxNLocator(5))
axarr[0].yaxis.set_major_formatter(ScalarFormatter(useOffset=False))
axarr[0].tick_params(direction='out', labelsize=FONT_SIZE)
axarr[0].grid(which='major', alpha=0.5)
axarr[0].grid(which='minor', alpha=0.2)

data = conv_dryer
x = range(0, len(data))

axarr[1].scatter(x, data)
axarr[1].set_ylabel('$T_\mathrm{dryer,2,2}$', size=FONT_SIZE)
axarr[1].yaxis.set_major_locator(MaxNLocator(5))
axarr[1].yaxis.set_major_formatter(ScalarFormatter(useOffset=False))
axarr[1].tick_params(direction='out', labelsize=FONT_SIZE)
axarr[1].grid(which='major', alpha=0.5)
axarr[1].grid(which='minor', alpha=0.2)

data = conv_lambda
x = range(0, len(data))

axarr[2].scatter(x, data)
axarr[2].set_xlabel('Iterationsschritte', size=FONT_SIZE)
axarr[2].xaxis.set_major_locator(MaxNLocator(integer=True))
axarr[2].set_ylabel('$\lambda$', size=FONT_SIZE)
axarr[2].yaxis.set_major_formatter(ScalarFormatter(useOffset=False))
axarr[2].yaxis.set_major_locator(MaxNLocator(5))
axarr[2].tick_params(direction='out', labelsize=FONT_SIZE)
axarr[2].grid(which='major', alpha=0.5)
axarr[2].grid(which='minor', alpha=0.2)
```

Response:
See the relevant documentation in general and specifically
```
from matplotlib.ticker import FormatStrFormatter

fig, ax = plt.subplots()

ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
```


Question:
Labeling boxplot in seaborn with median value How can I label each boxplot in a seaborn plot with the median value? E.g.
```
import seaborn as sns
sns.set_style("whitegrid")
tips = sns.load_dataset("tips")
ax = sns.boxplot(x="day", y="total_bill", data=tips)
```
How do I label each boxplot with the median or average value?

Response:
I love when people include sample datasets!
```
import seaborn as sns

sns.set_style("whitegrid")
tips = sns.load_dataset("tips")
box_plot = sns.boxplot(x="day",y="total_bill",data=tips)

medians = tips.groupby(['day'])['total_bill'].median()
vertical_offset = tips['total_bill'].median() * 0.05 # offset from median for display

for xtick in box_plot.get_xticks():
    box_plot.text(xtick,medians[xtick] + vertical_offset,medians[xtick],
            horizontalalignment='center',size='x-small',color='w',weight='semibold')
```


Question: Editing the date formatting of x-axis tick labels I am looking to edit the formatting of the dates on the x-axis. The picture below shows how they appear on my bar graph by default. I would like to remove the repetition of 'Dec' and '2012' and just have the actual date numbers along the x-axis. Any suggestions as to how I can do this?

Response:
In short:
```
import matplotlib.dates as mdates
myFmt = mdates.DateFormatter('%d')
ax.xaxis.set_major_formatter(myFmt)
```
Many examples on the matplotlib website. The one I most commonly use is here


Question:
Draw curved arrow that looks just like pyplot.arrow I use pyplot.arrow do draw some straight arrows, e.g.,
```
import matplotlib.pyplot as plt
import numpy as np

v={}
for i in range (1,4):
    v[i]=np.array([np.cos(-2*np.pi/3*i),np.sin(-2*np.pi/3*i)])

plt.arrow(.85*(.05*v[2]+.95*v[1])[0],.85*(.05*v[2]+.95*v[1])[1],.85*.9*(v[2]-v[1])[0],.85*.9*(v[2]-v[1])[1],width=0,head_width=.03,head_length=.045,length_includes_head=True,color="black")
plt.arrow(.85*(.05*v[3]+.95*v[2])[0],.85*(.05*v[3]+.95*v[2])[1],.85*.9*(v[3]-v[2])[0],.85*.9*(v[3]-v[2])[1],width=0,head_width=.03,head_length=.045,length_includes_head=True,color="black")
plt.arrow(.85*(.05*v[1]+.95*v[3])[0],.85*(.05*v[1]+.95*v[3])[1],.85*.9*(v[1]-v[3])[0],.85*.9*(v[1]-v[3])[1],width=0,head_width=.03,head_length=.045,length_includes_head=True,color="black")

plt.axes().set_xlim(-.5,1)
plt.axes().set_ylim(-np.sqrt(3)/2,np.sqrt(3)/2)
plt.axes().set_aspect(1)
plt.show()
```
Now I want to also draw some arrows that have circular curvature instead of being straight. I see that I can achieve this with pyplot.annotate() or patches.FancyArrowPatch with connectionstyle="arc3,rad=.5" or so. But these arrows look completely different from the pyplot.arrows and do not fit with the rest of my figures. And I don't know how I could pass something like connectionstyle to pyplot.arrow. Is there a way to draw curved arrows that look exactly like those that I get from pyplot.arrow?

Response:
You cannot plot curved arrows with pyplot.arrow. However, patches.FancyArrowPatch should offer all the options to get any arrow style you want, so the idea would be to use a FancyArrowPatch for the straight arrows as well, such that you can use the same style for all arrows.
```
import matplotlib.pyplot as plt
import matplotlib.patches as patches

plt.axes().set_xlim(-.5,0.5)
plt.axes().set_ylim(-0.9,0.7)
plt.axes().set_aspect(1)

style = "Simple, tail_width=0.5, head_width=4, head_length=8"
kw = dict(arrowstyle=style, color="k")

a1 = patches.FancyArrowPatch((-0.4, -0.6), (0, 0.6), **kw)
a2 = patches.FancyArrowPatch((0, 0.6), (0.4, -0.6), **kw)
a3 = patches.FancyArrowPatch((-0.4, -0.6), (0.4, -0.6),
                             connectionstyle="arc3,rad=.5", **kw)

for a in [a1, a2, a3]:
    plt.gca().add_patch(a)
plt.show()
```


Question: How to create a matplotlib bar chart with a threshold line? I'd like to know how to create a matplotlib bar chart with a threshold line, the part of bars above threshold line should have red color, and the parts below the threshold line should be green. Please provide me a simple example, I couldn't find anything on the web.

Response:
You can simply use axhline like this. See this documentation
```
# For your case
plt.axhline(y=threshold,linewidth=1, color='k')

# Another example - You can also define xmin and xmax
plt.axhline(y=5, xmin=0.5, xmax=3.5)
```


Question:
Pandas Plotting with Multi-Index After performing a groupby.sum() on a DataFrame I'm having some trouble trying to create my intended plot.
```py
import pandas as pd
import numpy as np

np.random.seed(365)
rows = 100
data = {'Month': np.random.choice(['2014-01', '2014-02', '2014-03', '2014-04'], size=rows),
        'Code': np.random.choice(['A', 'B', 'C'], size=rows),
        'ColA': np.random.randint(5, 125, size=rows),
        'ColB': np.random.randint(0, 51, size=rows),}
df = pd.DataFrame(data)

     Month Code  ColA  ColB
0  2014-03    C    59    47
1  2014-01    A    24     9
2  2014-02    C    77    50

dfg = df.groupby(['Code', 'Month']).sum()

              ColA  ColB
Code Month
A    2014-01   124   102
     2014-02   398   282
     2014-03   474   198
     2014-04   830   237
B    2014-01   477   300
     2014-02   591   167
     2014-03   522   192
     2014-04   367   169
C    2014-01   412   180
     2014-02   275   205
     2014-03   795   291
     2014-04   901   309
```
How can I create a subplot (kind='bar') for each Code, where the x-axis is the Month and the bars are ColA and ColB?

Response:
I found the unstack(level) method to work perfectly, which has the added benefit of not needing a priori knowledge about how many Codes there are.
```py
ax = dfg.unstack(level=0).plot(kind='bar', subplots=True, rot=0, figsize=(9, 7), layout=(2, 3))
plt.tight_layout()
```


Question:
Scatterplot without linear fit in seaborn I am wondering if there is a way to turn off the linear fit in seaborn's lmplot or if there is an equivalent function that just produces the scatterplot. Sure, I could also use matplotlib, however, I find the syntax and aesthetics in seaborn quite appealing. E.g,. I want to plot the following plot
```
import seaborn as sns
sns.set(style="ticks")

df = sns.load_dataset("anscombe")
sns.lmplot("x", "y", data=df, hue='dataset')
```
Without the linear fit like so:
```
from itertools import cycle
import numpy as np

import matplotlib.pyplot as plt

color_gen = cycle(('blue', 'lightgreen', 'red', 'purple', 'gray', 'cyan'))

for lab in np.unique(df['dataset']):
    plt.scatter(df.loc[df['dataset'] == lab, 'x'],
                df.loc[df['dataset'] == lab, 'y'],
                c=next(color_gen),
                label=lab)

plt.legend(loc='best')
```

Response:
set fit_reg argument to False:
```
sns.lmplot("x", "y", data=df, hue='dataset', fit_reg=False)
```


Question:
How to draw axis in the middle of the figure? I want to draw a figure in matplotib where the axis are displayed within the plot itself not on the side I have tried the following code from here:
```
import math
import numpy as np
import matplotlib.pyplot as plt

def sigmoid(x):
    a = []
    for item in x:
        a.append(1/(1+math.exp(-item)))
    return a

x = np.arange(-10., 10., 0.2)
sig = sigmoid(x)

plt.plot(x,sig)
plt.show()
```
The above code displays the figure like this: What I would like to draw is something as follows (image from Wikipedia) This question describes a similar problem, but it draws a reference line in the middle but no axis.

Response:
One way to do it is using spines:
```
import math
import numpy as np
import matplotlib.pyplot as plt

def sigmoid(x):
    a = []
    for item in x:
        a.append(1/(1+math.exp(-item)))
    return a

x = np.arange(-10., 10., 0.2)
sig = sigmoid(x)

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

# Move left y-axis and bottom x-axis to centre, passing through (0,0)
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('center')

# Eliminate upper and right axes
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

# Show ticks in the left and lower axes only
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

plt.plot(x,sig)
plt.show()
```
shows:


Question:
Matplotlib legends in subplot I would like to put legends inside each one of the subplots below. I've tried with plt.legend but it didn't work.
```
f, (ax1, ax2, ax3) = plt.subplots(3, sharex=True, sharey=True)
ax1.plot(xtr, color='r', label='Blue stars')
ax2.plot(ytr, color='g')
ax3.plot(ztr, color='b')
ax1.set_title('2012/09/15')
plt.legend([ax1, ax2, ax3],["HHZ 1", "HHN", "HHE"])
plt.show()
```
With the suggestion from atomh33ls:
```
ax1.legend("HHZ 1",loc="upper right")
ax2.legend("HHN",loc="upper right")
ax3.legend("HHE",loc="upper right")
```
The legend position is fixed, however it seems to have a problem with the strings, because each letter is placed in a new line. Does anyone knows how to fix it?

Response:
This should work:
```
ax1.plot(xtr, color='r', label='HHZ 1')
ax1.legend(loc="upper right")
ax2.plot(xtr, color='r', label='HHN')
ax2.legend(loc="upper right")
ax3.plot(xtr, color='r', label='HHE')
ax3.legend(loc="upper right")
```


Question:
Image is not displaying in Google Colab while using imshow() I am working on a project which requires functions from OpenCV to plot images. I am trying to display image using the below code in Google Colab. But nothing shows up in the output. Can anybody help me with this?
```
%pylab notebook
import cv2

testim = imread('butterfly.jpg')
figure()
imshow(testim)
plt.show()
```
Screenshot: Link to my Colab Notebook

Response: Google colab crashes if you try to display image using cv2.imshow() instead import from google.colab.patches import cv2_imshow and display using cv2_imshow()


Question:
Hide ticks but show tick labels I can remove the ticks with
```
ax.set_xticks([])
ax.set_yticks([])
```
but this removes the labels as well. Any way I can plot the tick labels but not the ticks and the spine

Response:
You can set the tick length to 0 using tick_params (http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.tick_params):
```
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1],[1])
ax.tick_params(axis=u'both', which=u'both',length=0)
plt.show()
```


Question: Is there a list of line styles in matplotlib? I'm writing a script that will do some plotting. I want it to plot several data series, each with its unique line style (not color). I can easily iterate through a list, but is there such a list already available in python?

Response:
According to the doc you could find them by doing this :
```
from matplotlib import lines
lines.lineStyles.keys()

```python
['', ' ', 'None', '--', '-.', '-', ':']
#Output
#```
#You can do the same with markers EDIT: In the latest versions, there are still the same styles, but you can vary the space between dots/lines.
```


Question:
Setting Yaxis in Matplotlib using Pandas Using Pandas to plot in IPython Notebook, I have several plots and because Matplotlib decides the Y axis it is setting them differently and we need to compare that data using the same range. From the Matplotlib doc it seems that I need to set ylim, but can't figure the syntax to do so. I have tried several variants on:
```
df2250.plot(); plt.ylim((100000,500000))
df2260.plot()
df5.plot()
```
I assume I'll need to apply the limits to each plot, but since I can't get one working...

Response:
DataFrame.plot() exposes a ylim parameter that sets the y axis limits:
```
df.plot(ylim=(0, 200))
```
I'm guessing this feature was added after Rutger's answer was accepted in 2013.


Question:
Label data points on plot If you want to label your plot points using python matplotlib, I used the following code.
```py
from matplotlib import pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

A = anyarray
B = anyotherarray

plt.plot(A,B)
for i,j in zip(A,B):
    ax.annotate('%s)' %j, xy=(i,j), xytext=(30,0), textcoords='offset points')
    ax.annotate('(%s,' %i, xy=(i,j))

plt.grid()
plt.show()
```
I know that xytext=(30,0) goes along with the textcoords and you use those 30,0 values to position the data label point, so it's on the y=0 and x=30 on its own little area. You need both the lines plotting i and j otherwise you only plot x or y data label. You get something like this out (note the labels only): It's not ideal, there is still some overlap.

Response:
How about print (x, y) at once.
```
from matplotlib import pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

ax.plot(A,B)
for xy in zip(A, B):                                       # <--
    ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data') # <--

ax.grid()
plt.show()
```


Question:
Plotting multiple line graph using pandas and matplotlib I have the following data in a pandas dataframe
```
date  template     score
0  20140605         0  0.138786
1  20140605         1  0.846441
2  20140605         2  0.766636
3  20140605         3  0.259632
4  20140605         4  0.497366
5  20140606         0  0.138139
6  20140606         1  0.845320
7  20140606         2  0.762876
8  20140606         3  0.261035
9  20140606         4  0.498010
```
For every day there will be 5 templates and each template will have a score. I want to plot the date in the x axis and score in the y axis and a separate line graph for each template in the same figure. Is it possible to do this using matplotlib?

Response:
You can use the groupby method:
```
data.groupby("template").plot(x="date", y="score")
```


Question:
Making a chart bigger in size I'm trying to get a bigger chart. However, the figure method from matplotlib does not seem to be working properly. I get a message, which is not an error:
```none
<matplotlib.figure.Figure at 0xa25f7f0>
```
My code:
```py
import pandas.io.data as web
import pandas as pd
import matplotlib.pyplot as plt

%matplotlib inline
...
plt.figure(figsize=(20,10))
df2['media']= df2['SPY']*.6 + df2['TLT']*.4
df2.plot()
plt.show()
```
What's wrong with my code?

Response:
You can skip the first plt.figure() and just use the argument figsize:
```
df2.plot(figsize=(20,10))
```
See docs.


Question:
Plot a histogram such that bar heights sum to 1 (probability) I'd like to plot a normalized histogram from a vector using matplotlib. I tried the following:
```
plt.hist(myarray, normed=True)
```
as well as:
```
plt.hist(myarray, normed=1)
```
but neither option produces a y-axis from [0, 1] such that the bar heights of the histogram sum to 1.

Response:
If you want the sum of all bars to be equal unity, weight each bin by the total number of values:
```
weights = np.ones_like(myarray) / len(myarray)
plt.hist(myarray, weights=weights)
```
Note for Python 2.x: add casting to float() for one of the operators of the division as otherwise you would end up with zeros due to integer division


Question:
Show only certain items in legend I currently am plotting a stacked bar graph of a large amount of taxonomic data, and only wish to show significant species in the legend (out of ~500 I wish to show ~25). Is there a simple way to do this? Below is the code I have:
```
labels=['0','20','40','60','80','100','120']
ax1=subj1df.plot(kind='barh', stacked=True,legend=True,cmap='Paired', grid=False)
legend(ncol=2,loc=2, bbox_to_anchor=(1.05, 1), borderaxespad=0.)
label1=['Baseline','8h','24h','48h','96h','120h']
ax1.set_yticklabels(label1, fontdict=None, minor=False)
plt.title('Subject 1 Phyla',fontweight='bold')
plt.savefig('Subject1Phyla.eps', format='eps', dpi=1000)
ax1.set_xticklabels(labels)
```
Edit: tried adding this to show only one legend entry, however only returns an empty legend:
```
h, l = ax1.get_legend_handles_labels()
legend(l[4],h[4],ncol=2,loc=2, bbox_to_anchor=(1.05, 1), borderaxespad=0.)
```

Response:
This works:
```
plt.plot([0, 4], [3,4])
plt.plot([0, 4], [2,3],label='_nolegend_') # element missing from legend
plt.plot([0, 4], [1,2])
plt.legend(['first', 'third'])
```


Question:
Relocating legend from GeoPandas plot I'm plotting a map with legends using the GeoPandas plotting function. When I plot, my legends appear in the upper right corner of the figure. Here is how it looks like: I wanted to move the legends to the lower part of the graph. I would normally would have done something like this for a normal matplotlib plot:
```
fig, ax = plt.subplots(1, figsize=(4.5,10))
lima_bank_num.plot(ax=ax, column='quant_cuts', cmap='Blues', alpha=1, legend=True)
ax.legend(loc='lower left')
```
However, this modification is not taken into account.

Response:
This could be done using the legend_kwds argument:
```
df.plot(column='values', legend=True, legend_kwds={'loc': 'lower right'});
```


Question:
Hide legend from seaborn pairplot I would like to hide the Seaborn pairplot legend. The official docs don't mention a keyword legend. Everything I tried using plt.legend didn't work. Please suggest the best way forward. Thanks!
```
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline

test = pd.DataFrame({
    'id': ['1','2','1','2','2','6','7','7','6','6'],
    'x': [123,22,356,412,54,634,72,812,129,110],
    'y':[120,12,35,41,45,63,17,91,112,151]})
sns.pairplot(x_vars='x', y_vars="y",
                 data=test,
                 hue = 'id',
                 height = 3)
```

Response:
Since _legend.remove() method won't work on some other seaborn plots, what about:
```
plt.legend([],[], frameon=False)
```


Question:
Show decimal places and scientific notation on the axis I am plotting some big numbers with matplotlib in a pyqt program using python 2.7. I have a y-axis that ranges from 1e+18 to 3e+18 (usually). I'd like to see each tick mark show values in scientific notation and with 2 decimal places. For example 2.35e+18 instead of just 2e+18 because values between 2e+18 and 3e+18 still read just 2e+18 for a few tickmarks. Here is an example of that problem.
```
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
x = np.linspace(0, 300, 20)
y = np.linspace(0,300, 20)
y = y*1e16
ax.plot(x,y)
ax.get_xaxis().set_major_formatter(plt.LogFormatter(10,  labelOnlyBase=False))
ax.get_yaxis().set_major_formatter(plt.LogFormatter(10,  labelOnlyBase=False))
plt.show()
```

Response:
This is really easy to do if you use the matplotlib.ticker.FormatStrFormatter as opposed to the LogFormatter. The following code will label everything with the format '%.2e':
```
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick

fig = plt.figure()

ax = fig.add_subplot(111)

x = np.linspace(0, 300, 20)

y = np.linspace(0,300, 20)
y = y*1e16

ax.plot(x,y)

ax.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.2e'))

plt.show()
```


Question: How to change the datetime tick label frequency Below shows a plot of simulated data, which contains the xticks that I want to modify. By default, the pd.df.plot chooses dates that are approximately 3 months apart as ticks. But what I want is each month being a tick. What is the best way to do this? What about seasonal ticks? Thank you in advance.

Response:
First of all you have to convert pandas date objects to python date objects. This conversion is needed because of matplotlib internal date conversion functions. Then use functions from matplotlib.dates to set desired formatter and tick positions like here:
```
import pandas as pd
import numpy as np
import matplotlib.pylab as plt
import matplotlib.dates as mdates

# convert date objects from pandas format to python datetime
index = pd.date_range(start = "2015-07-01", end = "2017-01-01", freq = "D")
index = [pd.to_datetime(date, format='%Y-%m-%d').date() for date in index]
data = np.random.randint(1,100, size=len(index))
df = pd.DataFrame(data=data,index=index, columns=['data'])
print (df.head())

ax = df.plot()
# set monthly locator
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=1))
# set formatter
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))
# set font and rotation for date tick labels
plt.gcf().autofmt_xdate()

plt.show()
```
For season labels you have to construct it by yourself and then set it with plt.setp function (for month 02 set label winter, 04 - spring etc.): plt.setp(new_labels, rotation=90, fontsize=9). head of df:
```
data
2015-07-01    26
2015-07-02    33
2015-07-03    46
2015-07-04    69
2015-07-05    17
```


Question:
matplotlib y-axis label on right side Is there a simple way to put the y-axis label on the right-hand side of the plot? I know that this can be done for the tick labels using ax.yaxis.tick_right(), but I would like to know if it can be done for the axis label as well. One idea which came to mind was to use
```
ax.yaxis.tick_right()
ax2 = ax.twinx()
ax2.set_ylabel('foo')
```
However, this doesn't have the desired effect of placing all labels (tick and axis labels) on the right-hand side, while preserving the extent of the y-axis. In short, I would like a way to move all the y-axis labels from the left to the right.

Response:
It looks like you can do it with:
```
ax.yaxis.set_label_position("right")
ax.yaxis.tick_right()
```
See here for an example.


Question: how to turn on minor ticks only on y axis How can I turn the minor ticks only on y axis on a linear vs linear plot? When I use the function minor_ticks_on to turn minor ticks on, they appear on both x and y axis.

Response:
Nevermind, I figured it out.
```
ax.tick_params(axis='x', which='minor', bottom=False)
```


Question: matplotlib values under cursor [duplicate] This question already has answers here: Interactive pixel information of an image (7 answers) Closed 10 years ago. I'm using matplotlib.imshow to get an interactive display of a 2D array. The x/y coordinate under the cursor is displayed at the bottom left of the window. Is it possible to also get the value of the array under the cursor as well?

Response:
You simply need to re-assign ax.format_coord. See this example from the documentation. (code lifted directly from example)
```
"""
Show how to modify the coordinate formatter to report the image "z"
value of the nearest pixel given x and y
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm

X = 10*np.random.rand(5,3)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(X, cmap=cm.jet, interpolation='nearest')

numrows, numcols = X.shape
def format_coord(x, y):
    col = int(x+0.5)
    row = int(y+0.5)
    if col>=0 and col<numcols and row>=0 and row<numrows:
        z = X[row,col]
        return 'x=%1.4f, y=%1.4f, z=%1.4f'%(x, y, z)
    else:
        return 'x=%1.4f, y=%1.4f'%(x, y)

ax.format_coord = format_coord
plt.show()
```


Question:
How to display all label values in matplotlib I have two lists, when I plot with the following code, the x axis only shows up to 12 (max is 15). May I know how can I show all of the values in x list to the x axis? Thanks in advance.
```
x = [4,5,6,7,8,9,10,11,12,13,14,15,0,1,2,3]
y = [10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160]
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(np.arange(len(x)), y, 'o')
ax1.set_xticklabels(x)
plt.show()
```
If I set minor=True in the set_xticklabels function, it shows me all x=2,4,6,8,..,16... but I want ALL values. P.S. My x axis is not sorted, should display as it shows.

Response:
The issue here is that the number of ticks -set automatically - isn’t the same as the number of points in your plot. To resolve this, set the number of ticks:
```
ax1.set_xticks(np.arange(len(x)))
```
Before the ax1.set_xticklabels(x) call.


Question:
How can I open the interactive matplotlib window in IPython notebook? I am using IPython with --pylab=inline and would sometimes like to quickly switch to the interactive, zoomable matplotlib GUI for viewing plots (the one that pops up when you plot something in a terminal Python console). How could I do that? Preferably without leaving or restarting my notebook. The problem with inline plots in IPy notebook is that they are of a limited resolution and I can't zoom into them to see some smaller parts. With the maptlotlib GUI that starts from a terminal, I can select a rectangle of the graph that I want to zoom into and the axes adjust accordingly. I tried experimenting with
```
from matplotlib import interactive
interactive(True)
```
and
```
interactive(False)
```
but that didn't do anything. I couldn't find any hint online either.

Response:
According to the documentation, you should be able to switch back and forth like this:
```

```python
%matplotlib inline
```

```python
plot(...)
```

```python
%matplotlib qt  # wx, gtk, osx, tk, empty uses default
```

```python
plot(...)
```
and that will pop up a regular plot window (a restart on the notebook may be necessary).
```


Question: Styling part of label in legend in matplotlib Is it possible to have part of the text of a legend in a particular style, let's say, bold or italic?

Response:
Write between $$ to force matplotlib to interpret it.
```
import matplotlib.pyplot as plt

plt.plot(range(10), range(10), label = "Normal text $\it{Italics}$")
plt.legend()
plt.show()
```


Question:
Creating labels where line appears in matplotlib figure I have a figure created in matplotlib (time-series data) over which are a series of
```
matplotlib.pyplot.axvline
```
lines. I would like to create labels on the plot that appear close to (probably on the RHS of the line and towards the top of the figure) these vertical lines.

Response:
You can use something like
```
plt.axvline(10)
plt.text(10.1,0,'blah',rotation=90)
```
you might have to play around with the x and y value in text to get it to align properly. You can find the more complete documentation here.


Question: How to set a single, main title above all the subplots I am using pyplot. I have 4 subplots. How to set a single, main title above all the subplots? title() sets it above the last subplot.

Response:
Use pyplot.suptitle or Figure.suptitle:
```
import matplotlib.pyplot as plt
import numpy as np

fig=plt.figure()
data=np.arange(900).reshape((30,30))
for i in range(1,5):
    ax=fig.add_subplot(2,2,i)
    ax.imshow(data)

fig.suptitle('Main title') # or plt.suptitle('Main title')
plt.show()
```


Question:
How do I write text in subscript in the axis labels and the legend? I have the following axis labels and legend.
```
plt.ylabel("ratio_2")
plt.xlabel("n_1")
plt.legend(('alpha_1','alpha_2' ), loc = 'best',shadow = True)
```

Response: Put dollar signs around the formula: plt.xlabel("$n_1$")


Question: Matplotlib imshow zoom function? I have several (27) images represented in 2D arrays that I am viewing with imshow(). I need to zoom in on the exact same spot in every image. I know I can manually zoom, but this is tedious and not precise enough. Is there a way to programmatically specify a specific section of the image to show instead of the entire thing?

Response:
You could use plt.xlim and plt.ylim to set the region to be plotted:
```
import matplotlib.pyplot as plt
import numpy as np

data=np.arange(9).reshape((3,3))
plt.imshow(data)
plt.xlim(0.5, 1.5)
plt.ylim(0.5,1.5)
plt.show()
```


Question:
Create stacked histogram from unequal length arrays I'd like to create a stacked histogram. If I have a single 2-D array, made of three equal length data sets, this is simple. Code and image below:
```
import numpy as np
from matplotlib import pyplot as plt

# create 3 data sets with 1,000 samples
mu, sigma = 200, 25
x = mu + sigma*np.random.randn(1000,3)

#Stack the data
plt.figure()
n, bins, patches = plt.hist(x, 30, stacked=True, density = True)
plt.show()
```
However, if I try similar code with three data sets of a different length the results are that one histogram covers up another. Is there any way I can do the stacked histogram with mixed length data sets?
```
##Continued from above
###Now as three separate arrays
x1 = mu + sigma*np.random.randn(990,1)
x2 = mu + sigma*np.random.randn(980,1)
x3 = mu + sigma*np.random.randn(1000,1)

#Stack the data
plt.figure()
plt.hist(x1, bins, stacked=True, density = True)
plt.hist(x2, bins, stacked=True, density = True)
plt.hist(x3, bins, stacked=True, density = True)
plt.show()
```

Response:
Well, this is simple. I just need to put the three arrays in a list.
```
##Continued from above
###Now as three separate arrays
x1 = mu + sigma*np.random.randn(990,1)
x2 = mu + sigma*np.random.randn(980,1)
x3 = mu + sigma*np.random.randn(1000,1)

#Stack the data
plt.figure()
plt.hist([x1,x2,x3], bins, stacked=True, density=True)
plt.show()
```


Question: Change x axes scale I created this plot using Matlab Using matplotlib, the x-axies draws large numbers such as 100000, 200000, 300000. I would like to have something like 1, 2, 3 and a 10^5 to indicate that it's actually 100000, 200000, 300000. Is there a simple way to create such scale in matplotlib?

Response:
Try using matplotlib.pyplot.ticklabel_format:
```
import matplotlib.pyplot as plt
...
plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))
```
This applies scientific notation (i.e. a x 10^b) to your x-axis tickmarks


Question: How do I display a single image in PyTorch? How do I display a PyTorch Tensor of shape (3, 224, 224) representing a 224x224 RGB image? Using plt.imshow(image) gives the error: TypeError: Invalid dimensions for image data

Response:
Given a Tensor representing the image, use .permute() to put the channels as the last dimension when passing them to matplotlib:
```
plt.imshow(tensor_image.permute(1, 2, 0))
```
Note: permute does not copy or allocate memory, and from_numpy() doesn't either.


Question:
Add points to the existing matplotlib scatter plot How to add points to the existing diagram? The straightforward solution is to plot a new scatter, adding new data.
```
ax.scatter(data[:,0], data[:,1], cmap = cmap, c = color_data)
ax.scatter(new_points_x, new_points_y, color='blue')
```
But if we want to add more points with new colors, there is a problem: we have to take into consideration all previously added points. It would be great if I could use a special function like
```
AddPoint(ax, new_point, color)
```
I want only add new points in new colors. I do NOT need any animations

Response:
To just add a new data with new colour, indeed calling again scatter will add the new points with the specified colour:
```
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(10)
a = np.random.rand(10)
plt.scatter(x, a, c='blue')
b = np.random.rand(10)
plt.scatter(x, b, c='red')
plt.show()
```


Question: Imshow: extent and aspect I'm writing a software system that visualizes slices and projections through a 3D dataset. I'm using matplotlib and specifically imshow to visualize the image buffers I get back from my analysis code. Since I'd like to annotate the images with plot axes, I use the extent keyword that imshow supplies to map the image buffer pixel coordinates to a data space coordinate system. Unfortuantely, matplotlib doesn't know about units. Say (taking an artificial example) that I want to plot an image with dimensions of 1000 m X 1 km. In that case the extent would be something like [0, 1000, 0, 1]. Even though the image array is square, since the aspect ratio implied by the extent keyword is 1000, the resulting plot axes also have an aspect ratio of 1000. Is it possible to force the aspect ratio of the plot while still keeping the automatically generated major tick marks and labels I get by using the extent keyword?

Response:
You can do it by setting the aspect of the image manually (or by letting it auto-scale to fill up the extent of the figure). By default, imshow sets the aspect of the plot to 1, as this is often what people want for image data. In your case, you can do something like:
```
import matplotlib.pyplot as plt
import numpy as np

grid = np.random.random((10,10))

fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, figsize=(6,10))

ax1.imshow(grid, extent=[0,100,0,1])
ax1.set_title('Default')

ax2.imshow(grid, extent=[0,100,0,1], aspect='auto')
ax2.set_title('Auto-scaled Aspect')

ax3.imshow(grid, extent=[0,100,0,1], aspect=100)
ax3.set_title('Manually Set Aspect')

plt.tight_layout()
plt.show()
```


Question: Matplotlib Contour Clabel Location I would like to control the location of matplotlib clabels on a contour plot, but without utilizing the manual=True flag in clabel. For example, I would like to specify an x-coordinate, and have labels created at the points that pass through this line. I see that you can get the location of the individual labels using get_position(), but I am stuck at that. Any help would be greatly appreciated. Thanks!

Response:
Yes, there now is a way to control label locations! https://github.com/matplotlib/matplotlib/pull/642
```
plt.figure()
CS = plt.contour(X, Y, Z)
manual_locations = [(-1, -1.4), (-0.62, -0.7), (-2, 0.5), (1.7, 1.2), (2.0, 1.4), (2.4, 1.7)]
plt.clabel(CS, inline=1, fontsize=10, manual=manual_locations)
```


Question:
python - uploading a plot from memory to s3 using matplotlib and boto This is my working script that generates a plot, saves it locally to disk, uploads to S3 and deletes the file:
```
plt.figure(figsize=(6,6))
plt.plot(x, y, 'bo')
plt.savefig('file_location')

conn = boto.s3.connect_to_region(
    region_name=AWS_REGION,
    aws_access_key_id=AWS_ACCESS_KEY_ID,
    aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
    calling_format=boto.s3.connection.OrdinaryCallingFormat()
    )
bucket = conn.get_bucket('bucket_name')
k = Key(bucket)
k.key = 'file_name'
k.set_contents_from_filename('file_location')

os.remove(file_location)
```
What I want is to skip the disk writing and upload the plot directly from memory. Any suggestions how to achieve that?

Response:
Putting it all together:
```
img_data = io.BytesIO()
plt.savefig(img_data, format='png')
img_data.seek(0)

s3 = boto3.resource('s3')
bucket = s3.Bucket(BUCKET_NAME)
bucket.put_object(Body=img_data, ContentType='image/png', Key=KEY)
```
Thanks @padraic-cunningham and @guyb7 for the tips!


Question:
How to remove grid lines I am using google colab for my project. I am getting grid lines on images even I am not writing them.
```
from matplotlib import pyplot as plt
%matplotlib inline
import cv2

img = cv2.imread('k15.jpg')

img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

plt.imshow(img)
```
for code like above, I am getting grid lines which is not the case when I run the same code in my python shell.

Response:
```
plt.imshow(myImage)
plt.grid(None)   <---- this should remove that white grid
```


Question:
raise LinAlgError("SVD did not converge") LinAlgError: SVD did not converge in matplotlib pca determination Code:
```py
import numpy
from matplotlib.mlab import PCA
file_name = "store1_pca_matrix.txt"
ori_data = numpy.loadtxt(file_name,dtype='float', comments='#', delimiter=None,
            converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0)
result = PCA(ori_data)
```
Though my input matrix is devoid of nan and inf, I do get the error below:
```py
raise LinAlgError("SVD did not converge")
LinAlgError: SVD did not converge
```
What's the problem?

Response:
This can happen when there are inf or nan values in the data. Use this to remove nan values:
```
ori_data.dropna(inplace=True)
```


Question:
How can I show figures separately? Say that I have two figures in matplotlib, with one plot per figure:
```
import matplotlib.pyplot as plt

f1 = plt.figure()
plt.plot(range(0,10))
f2 = plt.figure()
plt.plot(range(10,20))
```
Then I show both in one shot
```
plt.show()
```
Is there a way to show them separately, i.e. to show just f1? Or better: how can I manage the figures separately like in the following 'wishful' code (that doesn't work):
```
f1 = plt.figure()
f1.plot(range(0,10))
f1.show()
```

Response:
Sure. Add an Axes using add_subplot. (Edited import.) (Edited show.)
```
import matplotlib.pyplot as plt
f1 = plt.figure()
f2 = plt.figure()
ax1 = f1.add_subplot(111)
ax1.plot(range(0,10))
ax2 = f2.add_subplot(111)
ax2.plot(range(10,20))
plt.show()
```
Alternatively, use add_axes.
```
ax1 = f1.add_axes([0.1,0.1,0.8,0.8])
ax1.plot(range(0,10))
ax2 = f2.add_axes([0.1,0.1,0.8,0.8])
ax2.plot(range(10,20))
```


Question:
matplotlib get ylim values I'm using matplotlib to plot data (using plot and errorbar functions) from Python. I have to plot a set of totally separate and independent plots, and then adjust their ylim values so they can be easily visually compared. How can I retrieve the ylim values from each plot, so that I can take the min and max of the lower and upper ylim values, respectively, and adjust the plots so they can be visually compared? Of course, I could just analyze the data and come up with my own custom ylim values... but I'd like to use matplotlib to do that for me. Any suggestions on how to easily (and efficiently) do this? Here's my Python function that plots using matplotlib:
```
import matplotlib.pyplot as plt

def myplotfunction(title, values, errors, plot_file_name):

    # plot errorbars
    indices = range(0, len(values))
    fig = plt.figure()
    plt.errorbar(tuple(indices), tuple(values), tuple(errors), marker='.')

    # axes
    axes = plt.gca()
    axes.set_xlim([-0.5, len(values) - 0.5])
    axes.set_xlabel('My x-axis title')
    axes.set_ylabel('My y-axis title')

    # title
    plt.title(title)

    # save as file
    plt.savefig(plot_file_name)

    # close figure
    plt.close(fig)
```

Response: Just use axes.get_ylim(), it is very similar to set_ylim. From the docs: get_ylim() Get the y-axis range [bottom, top]


Question:
set ticks with logarithmic scale It seems that the set_xticks is not working in log scale:
```py
from matplotlib import pyplot as plt
fig1, ax1 = plt.subplots()
ax1.plot([10, 100, 1000], [1,2,3])
ax1.set_xscale('log')
ax1.set_xticks([20, 200, 500])
plt.show()
```
is it possible?

Response:
```py
import matplotlib
from matplotlib import pyplot as plt
fig1, ax1 = plt.subplots()
ax1.plot([10, 100, 1000], [1,2,3])
ax1.set_xscale('log')
ax1.set_xticks([20, 200, 500])
ax1.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
```
or
```py
ax1.get_xaxis().get_major_formatter().labelOnlyBase = False
plt.show()
```


Question:
3D Scatter Plot with Colorbar Borrowing from the example on the Matplotlib documentation page and slightly modifying the code,
```
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

def randrange(n, vmin, vmax):
    return (vmax-vmin)*np.random.rand(n) + vmin

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
n = 100
for c, m, zl, zh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]:
    xs = randrange(n, 23, 32)
    ys = randrange(n, 0, 100)
    zs = randrange(n, zl, zh)
    cs = randrange(n, 0, 100)
    ax.scatter(xs, ys, zs, c=cs, marker=m)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()
```
Will give a 3D scatter plot with different colors for each point (random colors in this example). What's the correct way to add a colorbar to the figure, since adding in plt.colorbar() or ax.colorbar() doesn't seem to work.

Response:
This produces a colorbar (though possibly not the one you need): Replace this line:
```
ax.scatter(xs, ys, zs, c=cs, marker=m)
```
with
```
p = ax.scatter(xs, ys, zs, c=cs, marker=m)
```
then use
```
fig.colorbar(p)
```
near the end


Question:
How to plot different groups of data from a dataframe into a single figure I have a temperature file with many years of temperature records in the format below:
```none
2012-04-12,16:13:09,20.6
2012-04-12,17:13:09,20.9
2012-04-12,18:13:09,20.6
2007-05-12,19:13:09,5.4
2007-05-12,20:13:09,20.6
2007-05-12,20:13:09,20.6
2005-08-11,11:13:09,20.6
2005-08-11,11:13:09,17.5
2005-08-13,07:13:09,20.6
2006-04-13,01:13:09,20.6
```
Every year has different numbers of time of records, so the pandas datetimeindices are all different. I want to plot the different year's data in the same figure for comparison: The X-axis is datetimeindices from Jan to Dec The Y-axis is the temperature How should I go about doing this?

Response:
Try:
```
ax = df1.plot()
df2.plot(ax=ax)
```


Question:
Plotting multiple different plots in one figure using Seaborn I am attempting to recreate the following plot from the book Introduction to Statistical learning using seaborn I specifically want to recreate this using seaborn's lmplot to create the first two plots and boxplot to create the second. The main problem is that lmplot creates a FacetGrid according to this answer which forces me to hackily add another matplotlib Axes for the boxplot. I was wondering if there was an easier way to achieve this. Below, I have to do quite a bit of manual manipulation to get the desired plot.
```py
seaborn_grid = sns.lmplot('value', 'wage', col='variable', hue='education', data=df_melt, sharex=False)
seaborn_grid.fig.set_figwidth(8)

left, bottom, width, height = seaborn_grid.fig.axes[0]._position.bounds
left2, bottom2, width2, height2 = seaborn_grid.fig.axes[1]._position.bounds
left_diff = left2 - left
seaborn_grid.fig.add_axes((left2 + left_diff, bottom, width, height))

sns.boxplot('education', 'wage', data=df_wage, ax = seaborn_grid.fig.axes[2])
ax2 = seaborn_grid.fig.axes[2]
ax2.set_yticklabels([])
ax2.set_xticklabels(ax2.get_xmajorticklabels(), rotation=30)
ax2.set_ylabel('')
ax2.set_xlabel('');

leg = seaborn_grid.fig.legends[0]
leg.set_bbox_to_anchor([0, .1, 1.5,1])
```
Which yields Sample data for DataFrames:
```py
df_melt = {
    'education': ['1. < HS Grad', '4. College Grad', '3. Some College', '4. College Grad', '2. HS Grad'],
    'value': [18, 24, 45, 43, 50],
    'variable': ['age', 'age', 'age', 'age', 'age'],
    'wage': [75.0431540173515, 70.47601964694451, 130.982177377461, 154.68529299563, 75.0431540173515]}

df_wage = {
    'education': ['1. < HS Grad', '4. College Grad', '3. Some College', '4. College Grad', '2. HS Grad'],
    'wage': [75.0431540173515, 70.47601964694451, 130.982177377461, 154.68529299563, 75.0431540173515]}
```

Response:
One possibility would be to NOT use lmplot(), but directly use regplot() instead. regplot() plots on the axes you pass as an argument with ax=. You lose the ability to automatically split your dataset according to a certain variable, but if you know beforehand the plots you want to generate, it shouldn't be a problem. Something like this:
```py
import matplotlib.pyplot as plt
import seaborn as sns

fig, axs = plt.subplots(ncols=3)
sns.regplot(x='value', y='wage', data=df_melt, ax=axs[0])
sns.regplot(x='value', y='wage', data=df_melt, ax=axs[1])
sns.boxplot(x='education',y='wage', data=df_melt, ax=axs[2])
```


Question:
How to add black border to matplotlib 2.0 `ax` object In Python 3? I've been using style sheets in matplotlib lately. I really like how clean the seaborn-white looks and I want to be able to add the border to other styles like ggplot or seaborn-whitegrid. How can I add a black border around my ax object from fig, ax = plt.subplots()?
```
import pandas as pd
import numpy  as np
from collections import *

Se_data = pd.Series(Counter(np.random.randint(0,10,100)))
with plt.style.context("seaborn-whitegrid"):
    fig, ax = plt.subplots()
    Se_data.plot(kind="barh", ax=ax, title="No Border")
with plt.style.context("seaborn-white"):
    fig, ax = plt.subplots()
    Se_data.plot(kind="barh", ax=ax, title="With Border")
```
In response to the answer below:
```
Se_data = pd.Series(Counter(np.random.randint(0,10,100)))
with plt.style.context("seaborn-whitegrid"):
    fig, ax = plt.subplots()
    Se_data.plot(kind="barh", ax=ax, title="No Border")
    ax.spines['bottom'].set_color('0.5')
    ax.spines['top'].set_color(None)
    ax.spines['right'].set_color('0.5')
    ax.spines['left'].set_color(None)
    ax.patch.set_facecolor('0.1')
    plt.grid(b=True, which='major', color='0.2', linestyle='-')
    plt.grid(b=True, which='minor', color='0.2', linestyle='-')
    ax.tick_params(axis='x', colors='0.7', which='both')
    ax.tick_params(axis='y', colors='0.7', which='both')
    ax.yaxis.label.set_color('0.9')
    ax.xaxis.label.set_color('0.9')
    ax.margins(5)
    fig.patch.set_facecolor('0.15')
```

Response:
Take a look at this. What you're looking for are these two lines:
```
ax.patch.set_edgecolor('black')

ax.patch.set_linewidth(1)
```


Question:
How to specify values on y axis of a matplotlib plot I need to generate a graph using matplotlib like the one in the attached picture. So far I tried it like this:
```py
import matplotlib.pyplot as plt
import numpy as np

x = np.array([0,1,2,3])
y = np.array([20,21,22,23])
my_xticks = ['John','Arnold','Mavis','Matt']
plt.xticks(x, my_xticks)
plt.plot(x, y)
plt.show()
```
How can I specify a different number of values on the y axis different from the number of values on the x axis? And maybe specify them as an interval with 0.005 difference instead of a list?

Response:
```
import matplotlib.pyplot as plt
import numpy as np

x = np.array([0,1,2,3])
y = np.array([0.650, 0.660, 0.675, 0.685])
my_xticks = ['a', 'b', 'c', 'd']
plt.xticks(x, my_xticks)
plt.yticks(np.arange(y.min(), y.max(), 0.005))
plt.plot(x, y)
plt.grid(axis='y', linestyle='-')
plt.show()
```
Something like this should work.


Question:
How do I plot in real-time in a while loop? I am trying to plot some data from a camera in real time using OpenCV. However, the real-time plotting (using matplotlib) doesn't seem to be working. I've isolated the problem into this simple example:
```
fig = plt.figure()
plt.axis([0, 1000, 0, 1])

i = 0
x = list()
y = list()

while i < 1000:
    temp_y = np.random.random()
    x.append(i)
    y.append(temp_y)
    plt.scatter(i, temp_y)
    i += 1
    plt.show()
```
I would expect this example to plot 1000 points individually. What actually happens is that the window pops up with the first point showing (ok with that), then waits for the loop to finish before it populates the rest of the graph. Any thoughts why I am not seeing points populated one at a time?

Response:
Here's the working version of the code in question (requires at least version Matplotlib 1.1.0 from 2011-11-14):
```
import numpy as np
import matplotlib.pyplot as plt

plt.axis([0, 10, 0, 1])

for i in range(10):
    y = np.random.random()
    plt.scatter(i, y)
    plt.pause(0.05)

plt.show()
```
Note the call to plt.pause(0.05), which both draws the new data and runs the GUI's event loop (allowing for mouse interaction).


Question:
Matplotlib subplots_adjust hspace so titles and xlabels don't overlap? [duplicate] This question already has answers here: Improve subplot size/spacing with many subplots (12 answers) Closed 2 years ago. With, say, 3 rows of subplots in matplotlib, xlabels of one row can overlap the title of the next. One has to fiddle with pl.subplots_adjust(hspace), which is annoying. Is there a recipe for hspace that prevents overlaps and works for any nrow?
```
""" matplotlib xlabels overlap titles ? """
import sys
import numpy as np
import pylab as pl

nrow = 3
hspace = .4  # of plot height, titles and xlabels both fall within this ??
exec "\n".join( sys.argv[1:] )  # nrow= ...

y = np.arange(10)
pl.subplots_adjust( hspace=hspace )

for jrow in range( 1, nrow+1 ):
    pl.subplot( nrow, 1, jrow )
    pl.plot( y**jrow )
    pl.title( 5 * ("title %d " % jrow) )
    pl.xlabel( 5 * ("xlabel %d " % jrow) )

pl.show()
```
My versions: matplotlib 0.99.1.1, Python 2.6.4, Mac OSX 10.4.11, backend: Qt4Agg (TkAgg => Exception in Tkinter callback) (For many extra points, can anyone outline how matplotlib's packer / spacer works, along the lines of chapter 17 "the packer" in the Tcl/Tk book?)

Response: The link posted by Jose has been updated and pylab now has a tight_layout() function that does this automatically (in matplotlib version 1.1.0). http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.tight_layout http://matplotlib.org/users/tight_layout_guide.html#plotting-guide-tight-layout


Question:
Bar plot with groupby My categorical variable case_status takes on four unique values. I have data from 2014 to 2016. I would like to plot the distribution of case_status grouped by year. I try the following:
```py
df.groupby('year').case_status.value_counts().plot.barh()
```
And I get the following plot: However, I want the following plot:

Response:
I think you need add unstack for DataFrame:
```
df.groupby('year').case_status.value_counts().unstack().plot.barh()
```
Also is possible change level:
```
df.groupby('year').case_status.value_counts().unstack(0).plot.barh()
```