Question: How to draw a line with matplotlib? I cannot find a way to draw an arbitrary line with matplotlib Python library. It allows to draw horizontal and vertical lines (with matplotlib.pyplot.axhline and matplotlib.pyplot.axvline, for example), but i do not see how to draw a line through two given points (x1, y1) and (x2, y2). Is there a way? Is there a simple way?

Response:
This will draw a line that passes through the points (-1, 1) and (12, 4), and another one that passes through the points (1, 3) et (10, 2) x1 are the x coordinates of the points for the first line, y1 are the y coordinates for the same -- the elements in x1 and y1 must be in sequence. x2 and y2 are the same for the other line.
```
import matplotlib.pyplot as plt
x1, y1 = [-1, 12], [1, 4]
x2, y2 = [1, 10], [3, 2]
plt.plot(x1, y1, x2, y2, marker = 'o')
plt.show()
```
I suggest you spend some time reading / studying the basic tutorials found on the very rich matplotlib website to familiarize yourself with the library. What if I don't want line segments? [edit]: As shown by @thomaskeefe, starting with matplotlib 3.3, this is now builtin as a convenience: plt.axline((x1, y1), (x2, y2)), rendering the following obsolete. There are no direct ways to have lines extend to infinity... matplotlib will either resize/rescale the plot so that the furthest point will be on the boundary and the other inside, drawing line segments in effect; or you must choose points outside of the boundary of the surface you want to set visible, and set limits for the x and y axis. As follows:
```
import matplotlib.pyplot as plt
x1, y1 = [-1, 12], [1, 10]
x2, y2 = [-1, 10], [3, -1]
plt.xlim(0, 8), plt.ylim(-2, 8)
plt.plot(x1, y1, x2, y2, marker = 'o')
plt.show()
```


Question:
Relationship between dpi and figure size I have created a figure using matplotlib but I have realized the plot axis and the drawn line gets zoomed out. Reading this earlier discussion thread, it explains how to set the figure size.
```
fig, ax = plt.subplots()
fig.set_size_inches(3, 1.5)
plt.savefig(file.jpeg, edgecolor='black', dpi=400, facecolor='black', transparent=True)
```
With the above code (other configurations removed for brevity), I do get a resulting image file with 1200 X 600 desired dimensions(should we say resolution too?) and desired file size. The projected image is scaled out in an unusual way, annotations for example are enlarged. While I can set the size of the labels on the axis, the figure doesn't look proportional with respect to the scale since the bottom and right spines are large and so are the plotted lines. The question, therefore, is, what configurations are going wrong?

Response:
Figure size (figsize) determines the size of the figure in inches. This gives the amount of space the axes (and other elements) have inside the figure. The default figure size is (6.4, 4.8) inches in matplotlib 2. A larger figure size will allow for longer texts, more axes or more ticklabels to be shown. Dots per inches (dpi) determines how many pixels the figure comprises. The default dpi in matplotlib is 100. A figure of figsize=(w,h) will have
```
px, py = w*dpi, h*dpi  # pixels
# e.g.
# 6.4 inches * 100 dpi = 640 pixels
```
So in order to obtain a figure with a pixel size of e.g. (1200,600) you may chose several combinations of figure size and dpi, e.g.
```
figsize=(15,7.5), dpi= 80
figsize=(12,6)  , dpi=100
figsize=( 8,4)  , dpi=150
figsize=( 6,3)  , dpi=200
etc.
```
Now, what is the difference? This is determined by the size of the elements inside the figure. Most elements like lines, markers, texts have a size given in points. Matplotlib figures use Points per inch (ppi) of 72. A line with thickness 1 point will be 1./72. inch wide. A text with fontsize 12 points will be 12./72. inch heigh. Of course if you change the figure size in inches, points will not change, so a larger figure in inches still has the same size of the elements. Changing the figure size is thus like taking a piece of paper of a different size. Doing so, would of course not change the width of the line drawn with the same pen. On the other hand, changing the dpi scales those elements. At 72 dpi, a line of 1 point size is one pixel strong. At 144 dpi, this line is 2 pixels strong. A larger dpi will therefore act like a magnifying glass. All elements are scaled by the magnifying power of the lens. A comparisson for constant figure size and varying dpi is shown in the image below on the left. On the right you see a constant dpi and varying figure size. Figures in each row have the same pixel size. Code to reproduce:
```
import matplotlib.pyplot as plt
%matplotlib inline

def plot(fs,dpi):
    fig, ax=plt.subplots(figsize=fs, dpi=dpi)
    ax.set_title("Figsize: {}, dpi: {}".format(fs,dpi))
    ax.plot([2,4,1,5], label="Label")
    ax.legend()

figsize=(2,2)
for i in range(1,4):
    plot(figsize, i*72)

dpi=72
for i in [2,4,6]:
    plot((i,i), dpi)
```


Question:
Get matplotlib color cycle state Is it possible to query the current state of the matplotlib color cycle? In other words is there a function get_cycle_state that will behave in the following way?
```

```python
plot(x1, y1)
```

```python
plot(x2, y2)
```

```python
state = get_cycle_state()
```

```python
print state
#Output
#2
#```
#Where I expect the state to be the index of the next color that will be used in a plot. Alternatively, if it returned the next color ("r" for the default cycle in the example above), that would be fine too.
```

Response:
Accessing the color cycle iterator There's no "user-facing" (a.k.a. "public") method to access the underlying iterator, but you can access it through "private" (by convention) methods. However, you'd can't get the state of an iterator without changing it. Setting the color cycle Quick aside: You can set the color/property cycle in a variety of ways (e.g. ax.set_color_cycle in versions =1.5). Have a look at the example here for version 1.5 or greater, or the previous style here. Accessing the underlying iterator However, while there's no public-facing method to access the iterable, you can access it for a given axes object (ax) through the _get_lines helper class instance. ax._get_lines is a touch confusingly named, but it's the behind-the-scenes machinery that allows the plot command to process all of the odd and varied ways that plot can be called. Among other things, it's what keeps track of what colors to automatically assign. Similarly, there's ax._get_patches_for_fill to control cycling through default fill colors and patch properties. At any rate, the color cycle iterable is ax._get_lines.color_cycle for lines and ax._get_patches_for_fill.color_cycle for patches. On matplotlib >=1.5, this has changed to use the cycler library, and the iterable is called prop_cycler instead of color_cycle and yields a dict of properties instead of only a color. All in all, you'd do something like:
```
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
color_cycle = ax._get_lines.color_cycle
# or ax._get_lines.prop_cycler on version >= 1.5
# Note that prop_cycler cycles over dicts, so you'll want next(cycle)['color']
```
You can't view the state of an iterator However, this object is a "bare" iterator. We can easily get the next item (e.g. next_color = next(color_cycle), but that means that the next color after that is what will be plotted. By design, there's no way to get the current state of an iterator without changing it. In v1.5 or greater, it would be nice to get the cycler object that's used, as we could infer its current state. However, the cycler object itself isn't accessible (publicly or privately) anywhere. Instead, only the itertools.cycle instance created from the cycler object is accessible. Either way, there's no way to get to the underlying state of the color/property cycler. Match the color of the previously plotted item instead In your case, it sounds like you're wanting to match the color of something that was just plotted. Instead of trying to determine what the color/property will be, set the color/etc of your new item based on the properties of what's plotted. For example, in the case you described, I'd do something like this:
```
import matplotlib.pyplot as plt
import numpy as np

def custom_plot(x, y, **kwargs):
    ax = kwargs.pop('ax', plt.gca())
    base_line, = ax.plot(x, y, **kwargs)
    ax.fill_between(x, 0.9*y, 1.1*y, facecolor=base_line.get_color(), alpha=0.5)

x = np.linspace(0, 1, 10)
custom_plot(x, x)
custom_plot(x, 2*x)
custom_plot(x, -x, color='yellow', lw=3)

plt.show()
```
It's not the only way, but its cleaner than trying to get the color of the plotted line before-hand, in this case.


Question:
How do I write a Latex formula in the legend of a plot using Matplotlib inside a .py file? I am writing a script in Python (.py file) and I am using Matplotlib to plot an array. I want to add a legend with a formula to the plot, but I haven't been able to do it. I have done this before in IPython or the terminal. In this case, writing something like this:
```
legend(ur'$The_formula$')
```
worked perfectly. However, this doesn't work when I call my .py script from the terminal/IPython.

Response:
The easiest way is to assign the label when you plot the data, e.g.:
```
import matplotlib.pyplot as plt
ax = plt.gca()  # or any other way to get an axis object
ax.plot(x, y, label=r'$\sin (x)$')

ax.legend()
```


Question: Drawing average line in histogram I am drawing a histogram using matplotlib in python, and would like to draw a line representing the average of the dataset, overlaid on the histogram as a dotted line (or maybe some other color would do too). Any ideas on how to draw a line overlaid on the histogram? I am using the plot() command, but not sure how to draw a vertical line (i.e. what value should I give for the y-axis? thanks!

Response:
You can use plot or vlines to draw a vertical line, but to draw a vertical line from the bottom to the top of the y axis, axvline is the probably the simplest function to use. Here's an example:
```

```python
import numpy as np
```

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

```python
np.random.seed(6789)
```

```python
x = np.random.gamma(4, 0.5, 1000)
```

```python
result = plt.hist(x, bins=20, color='c', edgecolor='k', alpha=0.65)
```

```python
plt.axvline(x.mean(), color='k', linestyle='dashed', linewidth=1)
#Output
#<matplotlib.lines.Line2D at 0x119758828>
#```
#Result:
```


Question:
How to remove lines in a Matplotlib plot How can I remove a line (or lines) of a matplotlib axes in such a way as it actually gets garbage collected and releases the memory back? The below code appears to delete the line, but never releases the memory (even with explicit calls to gc.collect())
```
from matplotlib import pyplot
import numpy
a = numpy.arange(int(1e7))
# large so you can easily see the memory footprint on the system monitor.
fig = pyplot.Figure()
ax  = pyplot.add_subplot(1, 1, 1)
lines = ax.plot(a) # this uses up an additional 230 Mb of memory.
# can I get the memory back?
l = lines[0]
l.remove()
del l
del lines
# not releasing memory
ax.cla() # this does release the memory, but also wipes out all other lines.
```
So is there a way to just delete one line from an axes and get the memory back? This potential solution also does not work.

Response:
This is a very long explanation that I typed up for a coworker of mine. I think it would be helpful here as well. Be patient, though. I get to the real issue that you are having toward the end. Just as a teaser, it's an issue of having extra references to your Line2D objects hanging around. WARNING: One other note before we dive in. If you are using IPython to test this out, IPython keeps references of its own and not all of them are weakrefs. So, testing garbage collection in IPython does not work. It just confuses matters. Okay, here we go. Each matplotlib object (Figure, Axes, etc) provides access to its child artists via various attributes. The following example is getting quite long, but should be illuminating. We start out by creating a Figure object, then add an Axes object to that figure. Note that ax and fig.axes[0] are the same object (same id()).
```

```python
#Create a figure
```

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

```python
fig.axes
#Output
#[]
```

```python
#Add an axes object
```

```python
ax = fig.add_subplot(1,1,1)
```

```python
#The object in ax is the same as the object in fig.axes[0], which is
```

```python
#   a list of axes objects attached to fig
```

```python
print ax
#Output
#Axes(0.125,0.1;0.775x0.8)
```

```python
print fig.axes[0]
#Output
#Axes(0.125,0.1;0.775x0.8)  #Same as "print ax"
```

```python
id(ax), id(fig.axes[0])
#Output
#(212603664, 212603664) #Same ids => same objects
#```
#This also extends to lines in an axes object:
#```
```

```python
#Add a line to ax
```

```python
lines = ax.plot(np.arange(1000))
```

```python
#Lines and ax.lines contain the same line2D instances
```

```python
print lines
#Output
#[<matplotlib.lines.Line2D object at 0xce84bd0>]
```

```python
print ax.lines
#Output
#[<matplotlib.lines.Line2D object at 0xce84bd0>]
```

```python
print lines[0]
#Output
#Line2D(_line0)
```

```python
print ax.lines[0]
#Output
#Line2D(_line0)
```

```python
#Same ID => same object
```

```python
id(lines[0]), id(ax.lines[0])
#Output
#(216550352, 216550352)
#```
#If you were to call plt.show() using what was done above, you would see a figure containing a set of axes and a single line: Now, while we have seen that the contents of lines and ax.lines is the same, it is very important to note that the object referenced by the lines variable is not the same as the object reverenced by ax.lines as can be seen by the following:
#```
```

```python
id(lines), id(ax.lines)
#Output
#(212754584, 211335288)
#```
#As a consequence, removing an element from lines does nothing to the current plot, but removing an element from ax.lines removes that line from the current plot. So:
#```
```

```python
#THIS DOES NOTHING:
```

```python
lines.pop(0)
```

```python
#THIS REMOVES THE FIRST LINE:
```

```python
ax.lines.pop(0)
#Output
#```
#So, if you were to run the second line of code, you would remove the Line2D object contained in ax.lines[0] from the current plot and it would be gone. Note that this can also be done via ax.lines.remove() meaning that you can save a Line2D instance in a variable, then pass it to ax.lines.remove() to delete that line, like so:
#```
```

```python
#Create a new line
```

```python
lines.append(ax.plot(np.arange(1000)/2.0))
```

```python
ax.lines
#Output
#[<matplotlib.lines.Line2D object at 0xce84bd0>,  <matplotlib.lines.Line2D object at 0xce84dx3>]
#```
#```
```

```python
#Remove that new line
```

```python
ax.lines.remove(lines[0])
```

```python
ax.lines
#Output
#[<matplotlib.lines.Line2D object at 0xce84dx3>]
#```
#All of the above works for fig.axes just as well as it works for ax.lines Now, the real problem here. If we store the reference contained in ax.lines[0] into a weakref.ref object, then attempt to delete it, we will notice that it doesn't get garbage collected:
#```
```

```python
#Create weak reference to Line2D object
```

```python
from weakref import ref
```

```python
wr = ref(ax.lines[0])
```

```python
print wr
#Output
#<weakref at 0xb758af8; to 'Line2D' at 0xb757fd0>
```

```python
print wr()
#Output
#<matplotlib.lines.Line2D at 0xb757fd0>
```

```python
#Delete the line from the axes
```

```python
ax.lines.remove(wr())
```

```python
ax.lines
#Output
#[]
```

```python
#Test weakref again
```

```python
print wr
#Output
#<weakref at 0xb758af8; to 'Line2D' at 0xb757fd0>
```

```python
print wr()
#Output
#<matplotlib.lines.Line2D at 0xb757fd0>
#```
#The reference is still live! Why? This is because there is still another reference to the Line2D object that the reference in wr points to. Remember how lines didn't have the same ID as ax.lines but contained the same elements? Well, that's the problem.
#```
```

```python
#Print out lines
```

```python
print lines
#Output
#[<matplotlib.lines.Line2D object at 0xce84bd0>,  <matplotlib.lines.Line2D object at 0xce84dx3>]
```

To fix this problem, we simply need to delete `lines`, empty it, or let it go out of scope.

```python
#Reinitialize lines to empty list
```

```python
lines = []
```

```python
print lines
#Output
#[]
```

```python
print wr
#Output
#<weakref at 0xb758af8; dead>
#```
#So, the moral of the story is, clean up after yourself. If you expect something to be garbage collected but it isn't, you are likely leaving a reference hanging out somewhere.
```


Question: Matplotlib/Pyplot: How to zoom subplots together? I have plots of 3-axis accelerometer time-series data (t,x,y,z) in separate subplots I'd like to zoom together. That is, when I use the "Zoom to Rectangle" tool on one plot, when I release the mouse all 3 plots zoom together. Previously, I simply plotted all 3 axes on a single plot using different colors. But this is useful only with small amounts of data: I have over 2 million data points, so the last axis plotted obscures the other two. Hence the need for separate subplots. I know I can capture matplotlib/pyplot mouse events (http://matplotlib.sourceforge.net/users/event_handling.html), and I know I can catch other events (http://matplotlib.sourceforge.net/api/backend_bases_api.html#matplotlib.backend_bases.ResizeEvent), but I don't know how to tell what zoom has been requested on any one subplot, and how to replicate it on the other two subplots. I suspect I have the all the pieces, and need only that one last precious clue... -BobC

Response:
The easiest way to do this is by using the sharex and/or sharey keywords when creating the axes:
```
from matplotlib import pyplot as plt

ax1 = plt.subplot(2,1,1)
ax1.plot(...)
ax2 = plt.subplot(2,1,2, sharex=ax1)
ax2.plot(...)
```


Question: Is there a parameter in matplotlib/pandas to have the Y axis of a histogram as percentage? I would like to compare two histograms by having the Y axis show the percentage of each column from the overall dataset size instead of an absolute value. Is that possible? I am using Pandas and matplotlib. Thanks

Response:
The density=True (normed=True for matplotlib < 2.2.0) returns a histogram for which np.sum(pdf * np.diff(bins)) equals 1. If you want the sum of the histogram to be 1 you can use Numpy's histogram() and normalize the results yourself.
```
x = np.random.randn(30)

fig, ax = plt.subplots(1,2, figsize=(10,4))

ax[0].hist(x, density=True, color='grey')

hist, bins = np.histogram(x)
ax[1].bar(bins[:-1], hist.astype(np.float32) / hist.sum(), width=(bins[1]-bins[0]), color='grey')

ax[0].set_title('normed=True')
ax[1].set_title('hist = hist / hist.sum()')
```
Btw: Strange plotting glitch at the first bin of the left plot.


Question: Plotting a 3d cube, a sphere and a vector I search how to plot something with less instruction as possible with Matplotlib but I don't find any help for this in the documentation. I want to plot the following things: a wireframe cube centered in 0 with a side length of 2 a "wireframe" sphere centered in 0 with a radius of 1 a point at coordinates [0, 0, 0] a vector that starts at this point and goes to [1, 1, 1] How to do that?

Response:
It is a little complicated, but you can draw all the objects by the following code:
```
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations

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

# draw cube
r = [-1, 1]
for s, e in combinations(np.array(list(product(r, r, r))), 2):
    if np.sum(np.abs(s-e)) == r[1]-r[0]:
        ax.plot3D(*zip(s, e), color="b")

# draw sphere
u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]
x = np.cos(u)*np.sin(v)
y = np.sin(u)*np.sin(v)
z = np.cos(v)
ax.plot_wireframe(x, y, z, color="r")

# draw a point
ax.scatter([0], [0], [0], color="g", s=100)

# draw a vector
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d

class Arrow3D(FancyArrowPatch):

    def __init__(self, xs, ys, zs, *args, **kwargs):
        FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
        self._verts3d = xs, ys, zs

    def draw(self, renderer):
        xs3d, ys3d, zs3d = self._verts3d
        xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
        self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
        FancyArrowPatch.draw(self, renderer)

a = Arrow3D([0, 1], [0, 1], [0, 1], mutation_scale=20,
            lw=1, arrowstyle="-|>", color="k")
ax.add_artist(a)
plt.show()
```


Question:
How to show two figures using matplotlib? I have some troubles while drawing two figures at the same time, not shown in a single plot. But according to the documentation, I wrote the code and only the figure one shows. I think maybe I lost something important. Could anyone help me to figure out? Thanks. (The *tlist_first* used in the code is a list of data.)
```
plt.figure(1)
plt.hist(tlist_first, bins=2000000, normed = True, histtype ="step", cumulative = True, color = 'g',label = 'first answer')
plt.ylabel('Percentage of answered questions')
plt.xlabel('Minutes elapsed after questions are posted')

plt.axvline(x = 30, ymin = 0, ymax = 1, color = 'r', linestyle = '--', label = '30 min')
plt.axvline(x = 60, ymin = 0, ymax = 1, color = 'c', linestyle = '--', label = '1 hour')
plt.legend()
plt.xlim(0,120)
plt.ylim(0,1)
plt.show()
plt.close() ### not working either with this line or without it

plt.figure(2)
plt.hist(tlist_first, bins=2000000, normed = True, histtype ="step", cumulative = True, color = 'g',label = 'first answer')

plt.ylabel('Percentage of answered questions')
plt.xlabel('Minutes elapsed after questions are posted')

plt.axvline(x = 240, ymin = 0, ymax = 1, color = 'r', linestyle = '--', label = '30 min')
plt.axvline(x = 1440, ymin = 0, ymax = 1, color = 'c', linestyle = '--', label = '1 hour')
plt.legend(loc= 4)
plt.xlim(0,2640)
plt.ylim(0,1)
plt.show()
```

Response:
Alternatively to calling plt.show() at the end of the script, you can also control each figure separately doing:
```
f = plt.figure(1)
plt.hist........
............
f.show()

g = plt.figure(2)
plt.hist(........
................
g.show()

raw_input()
```
In this case you must call raw_input to keep the figures alive. This way you can select dynamically which figures you want to show Note: raw_input() was renamed to input() in Python 3


Question:
Putting newline in matplotlib label with TeX in Python? How can I add a newline to a plot's label (e.g. xlabel or ylabel) in matplotlib? For example,
```
plt.bar([1, 2], [4, 5])
plt.xlabel("My x label")
plt.ylabel(r"My long label with $\Sigma_{C}$ math \n continues here")
```
Ideally I'd like the y-labeled to be centered too. Is there a way to do this? It's important that the label have both TeX (enclosed in '$') and the newline.

Response:
You can have the best of both worlds: automatic "escaping" of LaTeX commands and newlines:
```
plt.ylabel(r"My long label with unescaped {\LaTeX} $\Sigma_{C}$ math"
           "\n"  # Newline: the backslash is interpreted as usual
           r"continues here with $\pi$")
```
(instead of using three lines, separating the strings by single spaces is another option). In fact, Python automatically concatenates string literals that follow each other, and you can mix raw strings (r"…") and strings with character interpolation ("\n").


Question:
How to display custom values on a bar plot I'm looking to see how to do two things in Seaborn with using a bar chart to display values that are in the dataframe, but not in the graph. I'm looking to display the values of one field in a dataframe while graphing another. For example, below, I'm graphing 'tip', but I would like to place the value of 'total_bill' centered above each of the bars (i.e.325.88 above Friday, 1778.40 above Saturday, etc.) Is there a way to scale the colors of the bars, with the lowest value of 'total_bill' having the lightest color (in this case Friday) and the highest value of 'total_bill' having the darkest? Obviously, I'd stick with one color (i.e., blue) when I do the scaling. While I see that others think that this is a duplicate of another problem (or two), I am missing the part of how I use a value that is not in the graph as the basis for the label or the shading. How do I say, use total_bill as the basis. I'm sorry, but I just can't figure it out based on those answers. Starting with the following code,
```
import pandas as pd
import seaborn as sns
%matplotlib inline

df = pd.read_csv("https://raw.githubusercontent.com/wesm/pydata-book/1st-edition/ch08/tips.csv", sep=',')
groupedvalues = df.groupby('day').sum().reset_index()
g = sns.barplot(x='day', y='tip', data=groupedvalues)
```
I get the following result: Interim Solution:
```
for index, row in groupedvalues.iterrows():
    g.text(row.name, row.tip, round(row.total_bill, 2), color='black', ha="center")
```
On the shading, using the example below, I tried the following:
```
import pandas as pd
import seaborn as sns
%matplotlib inline

df = pd.read_csv("https://raw.githubusercontent.com/wesm/pydata-book/1st-edition/ch08/tips.csv", sep=',')
groupedvalues = df.groupby('day').sum().reset_index()

pal = sns.color_palette("Greens_d", len(data))
rank = groupedvalues.argsort().argsort()
g = sns.barplot(x='day', y='tip', data=groupedvalues)

for index, row in groupedvalues.iterrows():
    g.text(row.name, row.tip, round(row.total_bill, 2), color='black', ha="center")
```
But that gave me the following error: AttributeError: 'DataFrame' object has no attribute 'argsort' So I tried a modification:
```
import pandas as pd
import seaborn as sns
%matplotlib inline

df = pd.read_csv("https://raw.githubusercontent.com/wesm/pydata-book/1st-edition/ch08/tips.csv", sep=',')
groupedvalues = df.groupby('day').sum().reset_index()

pal = sns.color_palette("Greens_d", len(data))
rank = groupedvalues['total_bill'].rank(ascending=True)
g = sns.barplot(x='day', y='tip', data=groupedvalues, palette=np.array(pal[::-1])[rank])
```
and that leaves me with IndexError: index 4 is out of bounds for axis 0 with size 4

Response:
New in matplotlib 3.4.0 There is now a built-in Axes.bar_label to automatically label bar containers:
```py
ax = sns.barplot(x='day', y='tip', data=groupedvalues)
ax.bar_label(ax.containers[0]) # only 1 container needed unless using `hue`
```
For custom labels (e.g., tip bars with total_bill values), use the labels parameter:
```py
ax = sns.barplot(x='day', y='tip', data=groupedvalues)
ax.bar_label(ax.containers[0], labels=groupedvalues['total_bill'])
#                              ----------------------------------
```
For multi-group bar plots (i.e., with hue), there will be multiple bar containers that need to be iterated:
```py
ax = sns.barplot(x='day', y='tip', hue='sex', data=df)
for container in ax.containers:
    ax.bar_label(container)
```
More details: How to label percentage counts (fmt param) How to rotate labels (rotation param) How to vertically center labels (label_type param) How to add spacing to labels (padding param) Color-ranked version Is there a way to scale the colors of the bars, with the lowest value of total_bill having the lightest color (in this case Friday) and the highest value of total_bill having the darkest? Find the rank of each total_bill value: Either use Series.sort_values:
```py
ranks = groupedvalues.total_bill.sort_values().index
# Int64Index([1, 0, 3, 2], dtype='int64')
```
Or condense Ernest's Series.rank version by chaining Series.sub:
```py
ranks = groupedvalues.total_bill.rank().sub(1).astype(int).array
# [1, 0, 3, 2]
```
Then reindex the color palette using ranks:
```py
palette = sns.color_palette('Blues_d', len(ranks))
ax = sns.barplot(x='day', y='tip', palette=np.array(palette)[ranks], data=groupedvalues)
```


Question:
Matplotlib scatter plot legend I created a 4D scatter plot graph to represent different temperatures in a specific area. When I create the legend, the legend shows the correct symbol and color but adds a line through it. The code I'm using is:
```
colors=['b', 'c', 'y', 'm', 'r']
lo = plt.Line2D(range(10), range(10), marker='x', color=colors[0])
ll = plt.Line2D(range(10), range(10), marker='o', color=colors[0])
l = plt.Line2D(range(10), range(10), marker='o',color=colors[1])
a = plt.Line2D(range(10), range(10), marker='o',color=colors[2])
h = plt.Line2D(range(10), range(10), marker='o',color=colors[3])
hh = plt.Line2D(range(10), range(10), marker='o',color=colors[4])
ho = plt.Line2D(range(10), range(10), marker='x', color=colors[4])
plt.legend((lo,ll,l,a, h, hh, ho),('Low Outlier', 'LoLo','Lo', 'Average', 'Hi', 'HiHi', 'High Outlier'),numpoints=1, loc='lower left', ncol=3, fontsize=8)
```
I tried changing Line2D to Scatter and scatter. Scatter returned an error and scatter changed the graph and returned an error. With scatter, I changed the range(10) to the lists containing the data points. Each list contains either the x, y, or z variable.
```
lo = plt.scatter(xLOutlier, yLOutlier, zLOutlier, marker='x', color=colors[0])
ll = plt.scatter(xLoLo, yLoLo, zLoLo, marker='o', color=colors[0])
l = plt.scatter(xLo, yLo, zLo, marker='o',color=colors[1])
a = plt.scatter(xAverage, yAverage, zAverage, marker='o',color=colors[2])
h = plt.scatter(xHi, yHi, zHi, marker='o',color=colors[3])
hh = plt.scatter(xHiHi, yHiHi, zHiHi, marker='o',color=colors[4])
ho = plt.scatter(xHOutlier, yHOutlier, zHOutlier, marker='x', color=colors[4])
plt.legend((lo,ll,l,a, h, hh, ho),('Low Outlier', 'LoLo','Lo', 'Average', 'Hi', 'HiHi',     'High Outlier'),scatterpoints=1, loc='lower left', ncol=3, fontsize=8)
```
When I run this, the legend no longer exists, it is a small white box in the corner with nothing in it. Any advice?

Response:
2D scatter plot Using the scatter method of the matplotlib.pyplot module should work (at least with matplotlib 1.2.1 with Python 2.7.5), as in the example code below. Also, if you are using scatter plots, use scatterpoints=1 rather than numpoints=1 in the legend call to have only one point for each legend entry. In the code below I've used random values rather than plotting the same range over and over, making all the plots visible (i.e. not overlapping each other).
```
import matplotlib.pyplot as plt
from numpy.random import random

colors = ['b', 'c', 'y', 'm', 'r']

lo = plt.scatter(random(10), random(10), marker='x', color=colors[0])
ll = plt.scatter(random(10), random(10), marker='o', color=colors[0])
l  = plt.scatter(random(10), random(10), marker='o', color=colors[1])
a  = plt.scatter(random(10), random(10), marker='o', color=colors[2])
h  = plt.scatter(random(10), random(10), marker='o', color=colors[3])
hh = plt.scatter(random(10), random(10), marker='o', color=colors[4])
ho = plt.scatter(random(10), random(10), marker='x', color=colors[4])

plt.legend((lo, ll, l, a, h, hh, ho),
           ('Low Outlier', 'LoLo', 'Lo', 'Average', 'Hi', 'HiHi', 'High Outlier'),
           scatterpoints=1,
           loc='lower left',
           ncol=3,
           fontsize=8)

plt.show()
```
3D scatter plot To plot a scatter in 3D, use the plot method, as the legend does not support Patch3DCollection as is returned by the scatter method of an Axes3D instance. To specify the markerstyle you can include this as a positional argument in the method call, as seen in the example below. Optionally one can include argument to both the linestyle and marker parameters.
```
import matplotlib.pyplot as plt
from numpy.random import random
from mpl_toolkits.mplot3d import Axes3D

colors=['b', 'c', 'y', 'm', 'r']

ax = plt.subplot(111, projection='3d')

ax.plot(random(10), random(10), random(10), 'x', color=colors[0], label='Low Outlier')
ax.plot(random(10), random(10), random(10), 'o', color=colors[0], label='LoLo')
ax.plot(random(10), random(10), random(10), 'o', color=colors[1], label='Lo')
ax.plot(random(10), random(10), random(10), 'o', color=colors[2], label='Average')
ax.plot(random(10), random(10), random(10), 'o', color=colors[3], label='Hi')
ax.plot(random(10), random(10), random(10), 'o', color=colors[4], label='HiHi')
ax.plot(random(10), random(10), random(10), 'x', color=colors[4], label='High Outlier')

plt.legend(loc='upper left', numpoints=1, ncol=3, fontsize=8, bbox_to_anchor=(0, 0))

plt.show()
```


Question:
How to add line based on slope and intercept In R, there is a function called abline in which a line can be drawn on a plot based on the specification of the intercept (first argument) and the slope (second argument). For instance,
```
plot(1:10, 1:10)
abline(0, 1)
```
where the line with an intercept of 0 and the slope of 1 spans the entire range of the plot. Is there such a function in Matplotlib?

Response:
A lot of these solutions are focusing on adding a line to the plot that fits the data. Here's a simple solution for adding an arbitrary line to the plot based on a slope and intercept.
```
import matplotlib.pyplot as plt
import numpy as np

def abline(slope, intercept):
    """Plot a line from slope and intercept"""
    axes = plt.gca()
    x_vals = np.array(axes.get_xlim())
    y_vals = intercept + slope * x_vals
    plt.plot(x_vals, y_vals, '--')
```


Question: How to use matplotlib tight layout with Figure? [duplicate] This question already has answers here: Improve subplot size/spacing with many subplots (12 answers) Closed 2 years ago. I found tight_layout function for pyplot and want to use it. In my application I embed matplotlib plots into Qt GUI and use figure and not pyplot. Is there any way I can apply tight_layout there? Would it also work if I have several axes in one figure?

Response:
Just call fig.tight_layout() as you normally would. (pyplot is just a convenience wrapper. In most cases, you only use it to quickly generate figure and axes objects and then call their methods directly.) There shouldn't be a difference between the QtAgg backend and the default backend (or if there is, it's a bug). E.g.
```
import matplotlib.pyplot as plt

#-- In your case, you'd do something more like:
# from matplotlib.figure import Figure
# fig = Figure()
#-- ...but we want to use it interactive for a quick example, so
#--    we'll do it this way
fig, axes = plt.subplots(nrows=4, ncols=4)

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

plt.show()
```
Before Tight Layout After Tight Layout
```
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=4, ncols=4)

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

fig.tight_layout()

plt.show()
```


Question: Can i cycle through line styles in matplotlib I know how to cycle through a list of colors in matplotlib. But is it possible to do something similar with line styles (plain, dotted, dashed, etc.)? I'd need to do that so my graphs would be easier to read when printed. Any suggestions how to do that?

Response:
Something like this might do the trick:
```
import matplotlib.pyplot as plt
from itertools import cycle
lines = ["-","--","-.",":"]
linecycler = cycle(lines)
plt.figure()
for i in range(10):
    x = range(i,i+10)
    plt.plot(range(10),x,next(linecycler))
plt.show()
```
Result: Edit for newer version (v2.22)
```
import matplotlib.pyplot as plt
from cycler import cycler
#
plt.figure()
for i in range(5):
    x = range(i,i+5)
    linestyle_cycler = cycler('linestyle',['-','--',':','-.'])
    plt.rc('axes', prop_cycle=linestyle_cycler)
    plt.plot(range(5),x)
    plt.legend(['first','second','third','fourth','fifth'], loc='upper left', fancybox=True, shadow=True)
plt.show()
```
For more detailed information consult the matplotlib tutorial on "Styling with cycler" To see the output click "show figure"


Question: Barchart with vertical ytick labels I'm using matplotlib to generate a (vertical) barchart. The problem is my labels are rather long. Is there any way to display them vertically, either in the bar or above it or below it?

Response:
Do you mean something like this:
```

```python
from matplotlib import *
```

```python
plot(xrange(10))
```

```python
yticks(xrange(10), rotation='vertical')
#Output
#```
#? In general, to show any text in matplotlib with a vertical orientation, you can add the keyword rotation='vertical'. For further options, you can look at help(matplotlib.pyplot.text) The yticks function plots the ticks on the y axis; I am not sure whether you originally meant this or the ylabel function, but the procedure is alwasy the same, you have to add rotation='vertical' Maybe you can also find useful the options 'verticalalignment' and 'horizontalalignment', which allows you to define how to align the text with respect to the ticks or the other elements.
```


Question: What are the differences between add_axes and add_subplot? In a previous answer it was recommended to me to use add_subplot instead of add_axes to show axes correctly, but searching the documentation I couldn't understand when and why I should use either one of these functions. Can anyone explain the differences?

Response:
Common grounds Both, add_axes and add_subplot add an axes to a figure. They both return a (subclass of a) matplotlib.axes.Axes object. However, the mechanism which is used to add the axes differs substantially. add_axes The calling signature of add_axes is add_axes(rect), where rect is a list [x0, y0, width, height] denoting the lower left point of the new axes in figure coodinates (x0,y0) and its width and height. So the axes is positionned in absolute coordinates on the canvas. E.g.
```
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
```
places a figure in the canvas that is exactly as large as the canvas itself. add_subplot The calling signature of add_subplot does not directly provide the option to place the axes at a predefined position. It rather allows to specify where the axes should be situated according to a subplot grid. The usual and easiest way to specify this position is the 3 integer notation,
```
fig = plt.figure()
ax = fig.add_subplot(231)
```
In this example a new axes is created at the first position (1) on a grid of 2 rows and 3 columns. To produce only a single axes, add_subplot(111) would be used (First plot on a 1 by 1 subplot grid). (In newer matplotlib versions, add_subplot() without any arguments is possible as well.) The advantage of this method is that matplotlib takes care of the exact positioning. By default add_subplot(111) would produce an axes positioned at [0.125,0.11,0.775,0.77] or similar, which already leaves enough space around the axes for the title and the (tick)labels. However, this position may also change depending on other elements in the plot, titles set, etc. It can also be adjusted using pyplot.subplots_adjust(...) or pyplot.tight_layout(). In most cases, add_subplot would be the prefered method to create axes for plots on a canvas. Only in cases where exact positioning matters, add_axes might be useful. Example
```
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (5,3)

fig = plt.figure()
fig.add_subplot(241)
fig.add_subplot(242)
ax = fig.add_subplot(223)
ax.set_title("subplots")

fig.add_axes([0.77,.3,.2,.6])
ax2 =fig.add_axes([0.67,.5,.2,.3])
fig.add_axes([0.6,.1,.35,.3])
ax2.set_title("random axes")

plt.tight_layout()
plt.show()
```
Alternative The easiest way to obtain one or more subplots together with their handles is plt.subplots(). For one axes, use
```
fig, ax = plt.subplots()
```
or, if more subplots are needed,
```
fig, axes = plt.subplots(nrows=3, ncols=4)
```
The initial question In the initial question an axes was placed using fig.add_axes([0,0,1,1]), such that it sits tight to the figure boundaries. The disadvantage of this is of course that ticks, ticklabels, axes labels and titles are cut off. Therefore I suggested in one of the comments to the answer to use fig.add_subplot as this will automatically allow for enough space for those elements, and, if this is not enough, can be adjusted using pyplot.subplots_adjust(...) or pyplot.tight_layout().


Question:
Automatically run %matplotlib inline in IPython Notebook Every time I launch IPython Notebook, the first command I run is
```
%matplotlib inline
```
Is there some way to change my config file so that when I launch IPython, it is automatically in this mode?

Response:
The configuration way IPython has profiles for configuration, located at ~/.ipython/profile_*. The default profile is called profile_default. Within this folder there are two primary configuration files: ipython_config.py ipython_kernel_config.py Add the inline option for matplotlib to ipython_kernel_config.py:
```
c = get_config()
# ... Any other configurables you want to set
c.InteractiveShellApp.matplotlib = "inline"
```
matplotlib vs. pylab Usage of %pylab to get inline plotting is discouraged. It introduces all sorts of gunk into your namespace that you just don't need. %matplotlib on the other hand enables inline plotting without injecting your namespace. You'll need to do explicit calls to get matplotlib and numpy imported.
```
import matplotlib.pyplot as plt
import numpy as np
```
The small price of typing out your imports explicitly should be completely overcome by the fact that you now have reproducible code.


Question: How to create grouped boxplots Is there a way to group boxplots in matplotlib? Assume we have three groups "A", "B", and "C" and for each we want to create a boxplot for both "apples" and "oranges". If a grouping is not possible directly, we can create all six combinations and place them linearly side by side. What would be to simplest way to visualize the groupings? I'm trying to avoid setting the tick labels to something like "A + apples" since my scenario involves much longer names than "A".

Response:
How about using colors to differentiate between "apples" and "oranges" and spacing to separate "A", "B" and "C"? Something like this:
```
from pylab import plot, show, savefig, xlim, figure, \
                hold, ylim, legend, boxplot, setp, axes

# function for setting the colors of the box plots pairs
def setBoxColors(bp):
    setp(bp['boxes'][0], color='blue')
    setp(bp['caps'][0], color='blue')
    setp(bp['caps'][1], color='blue')
    setp(bp['whiskers'][0], color='blue')
    setp(bp['whiskers'][1], color='blue')
    setp(bp['fliers'][0], color='blue')
    setp(bp['fliers'][1], color='blue')
    setp(bp['medians'][0], color='blue')

    setp(bp['boxes'][1], color='red')
    setp(bp['caps'][2], color='red')
    setp(bp['caps'][3], color='red')
    setp(bp['whiskers'][2], color='red')
    setp(bp['whiskers'][3], color='red')
    setp(bp['fliers'][2], color='red')
    setp(bp['fliers'][3], color='red')
    setp(bp['medians'][1], color='red')

# Some fake data to plot
A= [[1, 2, 5,],  [7, 2]]
B = [[5, 7, 2, 2, 5], [7, 2, 5]]
C = [[3,2,5,7], [6, 7, 3]]

fig = figure()
ax = axes()
hold(True)

# first boxplot pair
bp = boxplot(A, positions = [1, 2], widths = 0.6)
setBoxColors(bp)

# second boxplot pair
bp = boxplot(B, positions = [4, 5], widths = 0.6)
setBoxColors(bp)

# thrid boxplot pair
bp = boxplot(C, positions = [7, 8], widths = 0.6)
setBoxColors(bp)

# set axes limits and labels
xlim(0,9)
ylim(0,9)
ax.set_xticklabels(['A', 'B', 'C'])
ax.set_xticks([1.5, 4.5, 7.5])

# draw temporary red and blue lines and use them to create a legend
hB, = plot([1,1],'b-')
hR, = plot([1,1],'r-')
legend((hB, hR),('Apples', 'Oranges'))
hB.set_visible(False)
hR.set_visible(False)

savefig('boxcompare.png')
show()
```


Question:
Superscript in Python plots I want to label my x axis at follows :
```
pylab.xlabel('metres 10^1')
```
But I don't want to have the ^ symbol included .
```
pylab.xlabel('metres 10$^{one}$')
```
This method works and will superscript letters but doesn't seem to work for numbers . If I try :
```
pylab.xlabel('metres 10$^1$')
```
It superscripts a letter N for some reason . Anyone know how to superscript numbers in python plots ? thanks .

Response:
You just need to have the full expression inside the $. Basically, you need "meters $10^1$". You don't need usetex=True to do this (or most any mathematical formula). You may also want to use a raw string (e.g. r"\t", vs "\t") to avoid problems with things like \n, \a, \b, \t, \f, etc. For example:
```
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.set(title=r'This is an expression $e^{\sin(\omega\phi)}$',
       xlabel='meters $10^1$', ylabel=r'Hertz $(\frac{1}{s})$')
plt.show()
```
If you don't want the superscripted text to be in a different font than the rest of the text, use \mathregular (or equivalently \mathdefault). Some symbols won't be available, but most will. This is especially useful for simple superscripts like yours, where you want the expression to blend in with the rest of the text.
```
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.set(title=r'This is an expression $\mathregular{e^{\sin(\omega\phi)}}$',
       xlabel='meters $\mathregular{10^1}$',
       ylabel=r'Hertz $\mathregular{(\frac{1}{s})}$')
plt.show()
```
For more information (and a general overview of matplotlib's "mathtext"), see: http://matplotlib.org/users/mathtext.html


Question:
How to draw grid lines behind matplotlib bar graph
```
x = ['01-02', '02-02', '03-02', '04-02', '05-02']
y = [2, 2, 3, 7, 2]

fig, ax = plt.subplots(1, 1)
ax.bar(range(len(y)), y, width=0.3,align='center',color='skyblue')
plt.xticks(range(len(y)), x, size='small')
plt.savefig('/home/user/graphimages/foo2.png')
plt.close()
```
I want to draw grid lines (of x & y) behind the bar graph.

Response:
To add a grid you simply need to add ax.grid() If you want the grid to be behind the bars then add
```
ax.grid(zorder=0)
ax.bar(range(len(y)), y, width=0.3, align='center', color='skyblue', zorder=3)
```
The important part is that the zorder of the bars is greater than grid. Experimenting it seems zorder=3 is the lowest value that actually gives the desired effect. I have no idea why zorder=1 isn't sufficient. EDIT: I have noticed this question has already been answered here using a different method although it suffers some link rot. Both methods yield the same result as far as I can see but andrew cooke's answer is more elegant.


Question:
How to hide axes and gridlines I would like to be able to hide the axes and gridlines on a 3D matplotlib graph. I want to do this because when zooming in and out the image gets pretty nasty. I'm not sure what code to include here but this is what I use to create the graph.
```
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.view_init(30, -90)
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")
plt.xlim(0,pL)
plt.ylim(0,pW)
ax.set_aspect("equal")

plt.show()
```
This is an example of the plot that I am looking at:

Response:
```
# Hide grid lines
ax.grid(False)

# Hide axes ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
```
Note, you need matplotlib>=1.2 for set_zticks() to work.


Question:
Pandas dataframe groupby plot I have a dataframe which is structured as:
```
Date   ticker  adj_close
0   2016-11-21     AAPL    111.730
1   2016-11-22     AAPL    111.800
2   2016-11-23     AAPL    111.230
3   2016-11-25     AAPL    111.790
4   2016-11-28     AAPL    111.570
...
8   2016-11-21      ACN    119.680
9   2016-11-22      ACN    119.480
10  2016-11-23      ACN    119.820
11  2016-11-25      ACN    120.740
...
```
How can I plot based on the ticker the adj_close versus Date?

Response:
Simple plot, you can use:
```
df.plot(x='Date',y='adj_close')
```
Or you can set the index to be Date beforehand, then it's easy to plot the column you want:
```
df.set_index('Date', inplace=True)
df['adj_close'].plot()
```
If you want a chart with one series by ticker on it You need to groupby before:
```
df.set_index('Date', inplace=True)
df.groupby('ticker')['adj_close'].plot(legend=True)
```
If you want a chart with individual subplots:
```
grouped = df.groupby('ticker')

ncols=2
nrows = int(np.ceil(grouped.ngroups/ncols))

fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12,4), sharey=True)

for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
    grouped.get_group(key).plot(ax=ax)

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


Question:
Histogram values of a Pandas Series I have some values in a Python Pandas Series (type: pandas.core.series.Series)
```

```python
series = pd.Series([0.0,950.0,-70.0,812.0,0.0,-90.0,0.0,0.0,-90.0,0.0,-64.0,208.0,0.0,-90.0,0.0,-80.0,0.0,0.0,-80.0,-48.0,840.0,-100.0,190.0,130.0,-100.0,-100.0,0.0,-50.0,0.0,-100.0,-100.0,0.0,-90.0,0.0,-90.0,-90.0,63.0,-90.0,0.0,0.0,-90.0,-80.0,0.0,])
```

```python
series.min()
#Output
#-100.0
```

```python
series.max()
#Output
#950.0
#```
#I would like to get values of histogram (not necessary plotting histogram)... I just need to get the frequency for each interval. Let's say that my intervals are going from [-200; -150] to [950; 1000] so lower bounds are
#```
#lwb = range(-200,1000,50)
#```
#and upper bounds are
#```
#upb = range(-150,1050,50)
#```
#I don't know how to get frequency (the number of values that are inside each interval) now... I'm sure that defining lwb and upb is not necessary... but I don't know what function I should use to perform this! (after diving in Pandas doc, I think cut function can help me because it's a discretization problem... but I'm don't understand how to use it) After being able to do this, I will have a look at the way to display histogram (but that's an other problem)
```

Response:
You just need to use the histogram function of NumPy:
```
import numpy as np
count, division = np.histogram(series)
```
where division is the automatically calculated border for your bins and count is the population inside each bin. If you need to fix a certain number of bins, you can use the argument bins and specify a number of bins, or give it directly the boundaries between each bin.
```
count, division = np.histogram(series, bins = [-201,-149,949,1001])
```
to plot the results you can use the matplotlib function hist, but if you are working in pandas each Series has its own handle to the hist function, and you can give it the chosen binning:
```
series.hist(bins=division)
```
Edit: As mentioned by another poster, Pandas is built on top of NumPy. Since OP is explicitly using Pandas, we can do away with the additional import by accessing NumPy through Pandas:
```py
count, division = pd.np.histogram(series)
```


Question:
matplotlib: drawing lines between points ignoring missing data I have a set of data which I want plotted as a line-graph. For each series, some data is missing (but different for each series). Currently matplotlib does not draw lines which skip missing data: for example
```
import matplotlib.pyplot as plt

xs = range(8)
series1 = [1, 3, 3, None, None, 5, 8, 9]
series2 = [2, None, 5, None, 4, None, 3, 2]

plt.plot(xs, series1, linestyle='-', marker='o')
plt.plot(xs, series2, linestyle='-', marker='o')

plt.show()
```
results in a plot with gaps in the lines. How can I tell matplotlib to draw lines through the gaps? (I'd rather not have to interpolate the data).

Response:
You can mask the NaN values this way:
```
import numpy as np
import matplotlib.pyplot as plt

xs = np.arange(8)
series1 = np.array([1, 3, 3, None, None, 5, 8, 9]).astype(np.double)
s1mask = np.isfinite(series1)
series2 = np.array([2, None, 5, None, 4, None, 3, 2]).astype(np.double)
s2mask = np.isfinite(series2)

plt.plot(xs[s1mask], series1[s1mask], linestyle='-', marker='o')
plt.plot(xs[s2mask], series2[s2mask], linestyle='-', marker='o')

plt.show()
```
This leads to


Question:
GridSpec with shared axes in Python This solution to another thread suggests using gridspec.GridSpec instead of plt.subplots. However, when I share axes between subplots, I usually use a syntax like the following
```
fig, axes = plt.subplots(N, 1, sharex='col', sharey=True, figsize=(3,18))
```
How can I specify sharex and sharey when I use GridSpec ?

Response:
First off, there's an easier workaround for your original problem, as long as you're okay with being slightly imprecise. Just reset the top extent of the subplots to the default after calling tight_layout:
```
fig, axes = plt.subplots(ncols=2, sharey=True)
plt.setp(axes, title='Test')
fig.suptitle('An overall title', size=20)

fig.tight_layout()
fig.subplots_adjust(top=0.9)

plt.show()
```
However, to answer your question, you'll need to create the subplots at a slightly lower level to use gridspec. If you want to replicate the hiding of shared axes like subplots does, you'll need to do that manually, by using the sharey argument to Figure.add_subplot and hiding the duplicated ticks with plt.setp(ax.get_yticklabels(), visible=False). As an example:
```
import matplotlib.pyplot as plt
from matplotlib import gridspec

fig = plt.figure()
gs = gridspec.GridSpec(1,2)
ax1 = fig.add_subplot(gs[0])
ax2 = fig.add_subplot(gs[1], sharey=ax1)
plt.setp(ax2.get_yticklabels(), visible=False)

plt.setp([ax1, ax2], title='Test')
fig.suptitle('An overall title', size=20)
gs.tight_layout(fig, rect=[0, 0, 1, 0.97])

plt.show()
```


Question:
Fitting a Normal distribution to 1D data I have a 1 dimensional array. I can compute the "mean" and "standard deviation" of this sample and plot the "Normal distribution" but I have a problem: I want to plot the data and Normal distribution in the same figure. I dont know how to plot both the data and the normal distribution. Any Idea about "Gaussian probability density function in scipy.stats"?
```
s = np.std(array)
m = np.mean(array)
plt.plot(norm.pdf(array,m,s))
```

Response:
You can use matplotlib to plot the histogram and the PDF (as in the link in @MrE's answer). For fitting and for computing the PDF, you can use scipy.stats.norm, as follows.
```
import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt

# Generate some data for this demonstration.
data = norm.rvs(10.0, 2.5, size=500)

# Fit a normal distribution to the data:
mu, std = norm.fit(data)

# Plot the histogram.
plt.hist(data, bins=25, density=True, alpha=0.6, color='g')

# Plot the PDF.
xmin, xmax = plt.xlim()
x = np.linspace(xmin, xmax, 100)
p = norm.pdf(x, mu, std)
plt.plot(x, p, 'k', linewidth=2)
title = "Fit results: mu = %.2f,  std = %.2f" % (mu, std)
plt.title(title)

plt.show()
```
Here's the plot generated by the script:


Question:
Delete a subplot I'm trying to figure out a way of deleting (dynamically) subplots in matplotlib. I see they have a remove method, but I get the error
```
NotImplementedError: cannot remove artist
```
I'm surprised that I can't find this anywhere. Does anyone know how to do this?
```py
from matplotlib import pyplot as plt

fig, axs = plt.subplots(1,3)

axs[0].plot([1,2],[3,4])
axs[2].plot([0,1],[2,3])

plt.draw()
plt.tight_layout()
```

Response:
Use fig.delaxes or plt.delaxes to remove unwanted subplots
```py
fig, axs = plt.subplots(1,3)
axs[0].plot([1,2],[3,4])
axs[2].plot([0,1],[2,3])

fig.delaxes(axs[1])

plt.draw()
plt.tight_layout()
```


Question:
Keras - Plot training, validation and test set accuracy I want to plot the output of this simple neural network:
```
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
history = model.fit(x_test, y_test, nb_epoch=10, validation_split=0.2, shuffle=True)

model.test_on_batch(x_test, y_test)
model.metrics_names
```
I have plotted accuracy and loss of training and validation:
```
print(history.history.keys())
#  "Accuracy"
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left')
plt.show()
# "Loss"
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left')
plt.show()
```
Now I want to add and plot test set's accuracy from model.test_on_batch(x_test, y_test), but from model.metrics_names I obtain the same value 'acc' utilized for plotting accuracy on training data plt.plot(history.history['acc']). How could I plot test set's accuracy?

Response:
```
import keras
from matplotlib import pyplot as plt
history = model1.fit(train_x, train_y,validation_split = 0.1, epochs=50, batch_size=4)
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
```
```
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
```


Question:
creating over 20 unique legend colors using matplotlib I am plotting 20 different lines on a single plot using matplotlib. I use a for loop for plotting and label every line with its key and then use the legend function
```
for key in dict.keys():
    plot(x,dict[key], label = key)
graph.legend()
```
But using this way, the graph repeats a lot of colors in the legend. Is there any way to ensure a unique color is assigned to each line using matplotlib and over 20 lines? thanks

Response:
The answer to your question is related to two other SO questions. The answer to How to pick a new color for each plotted line within a figure in matplotlib? explains how to define the default list of colors that is cycled through to pick the next color to plot. This is done with the Axes.set_color_cycle method. You want to get the correct list of colors though, and this is most easily done using a color map, as is explained in the answer to this question: Create a color generator from given colormap in matplotlib. There a color map takes a value from 0 to 1 and returns a color. So for your 20 lines, you want to cycle from 0 to 1 in steps of 1/20. Specifically you want to cycle form 0 to 19/20, because 1 maps back to 0. This is done in this example:
```
import matplotlib.pyplot as plt
import numpy as np

NUM_COLORS = 20

cm = plt.get_cmap('gist_rainbow')
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_prop_cycle(color=[cm(1.*i/NUM_COLORS) for i in range(NUM_COLORS)])
for i in range(NUM_COLORS):
    ax.plot(np.arange(10)*(i+1))

fig.savefig('moreColors.png')
plt.show()
```
This is the resulting figure: Alternative, better (debatable) solution There is an alternative way that uses a ScalarMappable object to convert a range of values to colors. The advantage of this method is that you can use a non-linear Normalization to convert from line index to actual color. The following code produces the same exact result:
```
import matplotlib.pyplot as plt
import matplotlib.cm as mplcm
import matplotlib.colors as colors
import numpy as np

NUM_COLORS = 20

cm = plt.get_cmap('gist_rainbow')
cNorm  = colors.Normalize(vmin=0, vmax=NUM_COLORS-1)
scalarMap = mplcm.ScalarMappable(norm=cNorm, cmap=cm)
fig = plt.figure()
ax = fig.add_subplot(111)
# old way:
#ax.set_prop_cycle(color=[cm(1.*i/NUM_COLORS) for i in range(NUM_COLORS)])
# new way:
ax.set_prop_cycle(color=[scalarMap.to_rgba(i) for i in range(NUM_COLORS)])
for i in range(NUM_COLORS):
    ax.plot(np.arange(10)*(i+1))

fig.savefig('moreColors.png')
plt.show()
```


Question:
Reset color cycle in Matplotlib Say I have data about 3 trading strategies, each with and without transaction costs. I want to plot, on the same axes, the time series of each of the 6 variants (3 strategies * 2 trading costs). I would like the "with transaction cost" lines to be plotted with alpha=1 and linewidth=1 while I want the "no transaction costs" to be plotted with alpha=0.25 and linewidth=5. But I would like the color to be the same for both versions of each strategy. I would like something along the lines of:
```
fig, ax = plt.subplots(1, 1, figsize=(10, 10))

for c in with_transaction_frame.columns:
    ax.plot(with_transaction_frame[c], label=c, alpha=1, linewidth=1)

****SOME MAGIC GOES HERE TO RESET THE COLOR CYCLE

for c in no_transaction_frame.columns:
    ax.plot(no_transaction_frame[c], label=c, alpha=0.25, linewidth=5)

ax.legend()
```
What is the appropriate code to put on the indicated line to reset the color cycle so it is "back to the start" when the second loop is invoked?

Response:
In Matplotlib <1.5.0, you can reset the colorcycle to the original with Axes.set_color_cycle. Looking at the code for this, there is a function to do the actual work:
```
def set_color_cycle(self, clist=None):
    if clist is None:
        clist = rcParams['axes.color_cycle']
    self.color_cycle = itertools.cycle(clist)
```
And a method on the Axes which uses it:
```
def set_color_cycle(self, clist):
    """
    Set the color cycle for any future plot commands on this Axes.

    *clist* is a list of mpl color specifiers.
    """
    self._get_lines.set_color_cycle(clist)
    self._get_patches_for_fill.set_color_cycle(clist)
```
This basically means you can call the set_color_cycle with None as the only argument, and it will be replaced with the default cycle found in rcParams['axes.color_cycle']. I tried this with the following code and got the expected result:
```
import matplotlib.pyplot as plt
import numpy as np

for i in range(3):
    plt.plot(np.arange(10) + i)

# for Matplotlib version < 1.5
plt.gca().set_color_cycle(None)
# for Matplotlib version >= 1.5
plt.gca().set_prop_cycle(None)

for i in range(3):
    plt.plot(np.arange(10, 1, -1) + i)

plt.show()
```


Question:
Change figure size and figure format in matplotlib [duplicate] This question already has answers here: How do I change the size of figures drawn with Matplotlib? (16 answers) Closed 4 years ago. I want to obtain fig1 exactly of 4 by 3 inch sized, and in tiff format correcting the program below:
```py
import matplotlib.pyplot as plt

list1 = [3,4,5,6,9,12]
list2 = [8,12,14,15,17,20]

plt.plot(list1, list2)
plt.savefig('fig1.png', dpi = 300)
plt.close()
```

Response:
You can set the figure size if you explicitly create the figure with
```
plt.figure(figsize=(3,4))
```
You need to set figure size before calling plt.plot() To change the format of the saved figure just change the extension in the file name. However, I don't know if any of matplotlib backends support tiff


Question: How to embed matplotlib in pyqt I want to embed a graph in a pyqt4 user interface. I do not understand how people did the embedding in the examples I found - this one (at the bottom) and that one. Could anyone post a step-by-step explanation or at least a very small, very simple code only creating e.g. a graph and a button in one pyqt4 GUI.

Response:
It is not that complicated actually. Relevant Qt widgets are in matplotlib.backends.backend_qt4agg. FigureCanvasQTAgg and NavigationToolbar2QT are usually what you need. These are regular Qt widgets. You treat them as any other widget. Below is a very simple example with a Figure, Navigation and a single button that draws some random data. I've added comments to explain things.
```
import sys
from PyQt4 import QtGui

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure

import random

class Window(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        # a figure instance to plot on
        self.figure = Figure()

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        # Just some button connected to `plot` method
        self.button = QtGui.QPushButton('Plot')
        self.button.clicked.connect(self.plot)

        # set the layout
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.button)
        self.setLayout(layout)

    def plot(self):
        ''' plot some random stuff '''
        # random data
        data = [random.random() for i in range(10)]

        # create an axis
        ax = self.figure.add_subplot(111)

        # discards the old graph
        ax.clear()

        # plot data
        ax.plot(data, '*-')

        # refresh canvas
        self.canvas.draw()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    main = Window()
    main.show()

    sys.exit(app.exec_())
```
Edit: Updated to reflect comments and API changes. NavigationToolbar2QTAgg changed with NavigationToolbar2QT Directly import Figure instead of pyplot Replace deprecated ax.hold(False) with ax.clear()


Question: How to prevent numbers being changed to exponential form in a plot I'm using Matplotlib in Python to plot simple x-y datasets. This produces nice-looking graphs, although when I "zoom in" too close on various sections of the plotted graph using the Figure View (which appears when you execute plt.show() ), the x-axis values change from standard number form (1050, 1060, 1070 etc.) to scientific form with exponential notation (e.g. 1, 1.5, 2.0 with the x-axis label given as +1.057e3). I'd prefer my figures to retain the simple numbering of the axis, rather than using exponential form. Is there a way I can force Matplotlib to do this?

Response:
The formatting of tick labels is controlled by a Formatter object, which assuming you haven't done anything fancy will be a ScalerFormatterby default. This formatter will use a constant shift if the fractional change of the values visible is very small. To avoid this, simply turn it off:
```
plt.plot(arange(0,100,10) + 1000, arange(0,100,10))
ax = plt.gca()
ax.get_xaxis().get_major_formatter().set_useOffset(False)
plt.draw()
```
If you want to avoid scientific notation in general,
```
ax.get_xaxis().get_major_formatter().set_scientific(False)
```
Can control this with globally via the axes.formatter.useoffset rcparam.


Question: How to generate audio from a numpy array? I want to create "heart rate monitor" effect from a 2D array in numpy and want the tone to reflect the values in the array.

Response:
You can use the write function from scipy.io.wavfile to create a wav file which you can then play however you wish. Note that the array must be integers, so if you have floats, you might want to scale them appropriately:
```
import numpy as np
from scipy.io.wavfile import write

rate = 44100
data = np.random.uniform(-1, 1, rate) # 1 second worth of random samples between -1 and 1
scaled = np.int16(data / np.max(np.abs(data)) * 32767)
write('test.wav', rate, scaled)
```
If you want Python to actually play audio, then this page provides an overview of some of the packages/modules.


Question:
How to recover matplotlib defaults after setting stylesheet In an ipython notebook, I used a matplotlib stylesheet to change the look of my plots using
```
from matplotlib.pyplot import *
%matplotlib inline
style.use('ggplot')
```
My version of matplotlib is 1.4.0. How do I go back to the default matplotlib styling? I tried all the available styles in
```
print style.available
```
but there doesn't seem to be a "default" option. I also tried
```
matplotlib.rcdefaults()
```
For some reason, this gives me a gray background. It also changes the text from gray (ggplot style) to black, which may be the default, but also could be another random style.

Response:
You should be able to set it back to default by:
```
import matplotlib as mpl
mpl.rcParams.update(mpl.rcParamsDefault)
```
In ipython, things are a little different, especially with inline backend:
```

```python
%matplotlib inline
```

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

```python
inline_rc = dict(mpl.rcParams)
```

```python
plt.plot(range(10))
#Output
#[<matplotlib.lines.Line2D at 0x72d2510>]
#```
#```
```

```python
mpl.rcParams.update(mpl.rcParamsDefault)
plt.plot(range(10))
#Output
#[<matplotlib.lines.Line2D at 0x7354730>]
#```
#```
```

```python
mpl.rcParams.update(inline_rc)
plt.plot(range(10))
#Output
#[<matplotlib.lines.Line2D at 0x75a8e10>]
#```
#Basically, %matplotlib inline uses its own rcParams. You can grab that from the source, but the arguably easier way is probably just save the rcParams as inline_rc after %matplotlib inline cell magic in this example, and reuse that later.
```


Question: How to overplot a line on a scatter plot in python? I have two vectors of data and I've put them into pyplot.scatter(). Now I'd like to over plot a linear fit to these data. How would I do this? I've tried using scikitlearn and np.polyfit().

Response:
```
import numpy as np
from numpy.polynomial.polynomial import polyfit
import matplotlib.pyplot as plt

# Sample data
x = np.arange(10)
y = 5 * x + 10

# Fit with polyfit
b, m = polyfit(x, y, 1)

plt.plot(x, y, '.')
plt.plot(x, b + m * x, '-')
plt.show()
```


Question:
How to set font size of Matplotlib axis Legend? I have a code like this:
```
import matplotlib.pyplot as plt
from matplotlib.pyplot import *
from matplotlib.font_manager import FontProperties

fontP = FontProperties()
fontP.set_size('xx-small')
fig=plt.figure()
ax1=fig.add_subplot(111)
plot([1,2,3], label="test1")
ax1.legend(loc=0, ncol=1, bbox_to_anchor=(0, 0, 1, 1),
           prop = fontP,fancybox=True,shadow=False,title='LEGEND')
plt.show()
```
It can be seen in the plot that the setting in Fontsize does not affect the Legend Title font size. How to set the font size of the legend title to a smaller size?

Response:
This is definitely an old question, but was frustrating me too and none of the other answers changed the legend title fontsize at all, but instead just changed the rest of the text. So after banging my head against the matplotlib documentation for awhile I came up with this.
```
legend = ax1.legend(loc=0, ncol=1, bbox_to_anchor=(0, 0, 1, 1),
           prop = fontP,fancybox=True,shadow=False,title='LEGEND')

plt.setp(legend.get_title(),fontsize='xx-small')
```
As of Matplotlib 3.0.3, you can also set it globally with
```
plt.rcParams['legend.title_fontsize'] = 'xx-small'
```


Question: Difference between "axes" and "axis" in matplotlib? I'm confused about what the different between axes and axis is in matplotlib. Could someone please explain in an easy-to-understand way?

Response: This figure from the documentation will answer your question: You can find this image here (in the Matplotlib 1.x docs); it's actually been replaced in the Matplotlib 2.x docs.


Question:
Matplotlib xticks not lining up with histogram I'm generating some histograms with matplotlib and I'm having some trouble figuring out how to get the xticks of a histogram to align with the bars. Here's a sample of the code I use to generate the histogram:
```
from matplotlib import pyplot as py

py.hist(histogram_data, 49, alpha=0.75)
py.title(column_name)
py.xticks(range(49))
py.show()
```
I know that all of values in the histogram_data array are in [0,1,...,48]. Which, assuming I did the math right, means there are 49 unique values. I'd like to show a histogram of each of those values. Here's a picture of what's generated. How can I set up the graph such that all of the xticks are aligned to the left, middle or right of each of the bars?

Response:
Short answer: Use plt.hist(data, bins=range(50)) instead to get left-aligned bins, plt.hist(data, bins=np.arange(50)-0.5) to get center-aligned bins, etc. Also, if performance matters, because you want counts of unique integers, there are a couple of slightly more efficient methods (np.bincount) that I'll show at the end. Problem Statement As a stand-alone example of what you're seeing, consider the following:
```
import matplotlib.pyplot as plt
import numpy as np

# Generate a random array of integers between 0-9
# data.min() will be 0 and data.max() will be 9 (not 10)
data = np.random.randint(0, 10, 1000)

plt.hist(data, bins=10)
plt.xticks(range(10))
plt.show()
```
As you've noticed, the bins aren't aligned with integer intervals. This is basically because you asked for 10 bins between 0 and 9, which isn't quite the same as asking for bins for the 10 unique values. The number of bins you want isn't exactly the same as the number of unique values. What you actually should do in this case is manually specify the bin edges. To explain what's going on, let's skip matplotlib.pyplot.hist and just use the underlying numpy.histogram function. For example, let's say you have the values [0, 1, 2, 3]. Your first instinct would be to do:
```

```python
import numpy as np
```

```python
np.histogram([0, 1, 2, 3], bins=4)
#Output
#(array([1, 1, 1, 1]), array([ 0.  ,  0.75,  1.5 ,  2.25,  3.  ]))
#```
#The first array returned is the counts and the second is the bin edges (in other words, where bar edges would be in your plot). Notice that we get the counts we'd expect, but because we asked for 4 bins between the min and max of the data, the bin edges aren't on integer values. Next, you might try:
#```
```

```python
np.histogram([0, 1, 2, 3], bins=3)
#Output
#(array([1, 1, 2]), array([ 0.,  1.,  2.,  3.]))
#```
#Note that the bin edges (the second array) are what you were expecting, but the counts aren't. That's because the last bin behaves differently than the others, as noted in the documentation for numpy.histogram:
#```
#Notes
#-----
#All but the last (righthand-most) bin is half-open.  In other words, if
#`bins` is::
#
#  [1, 2, 3, 4]
#
#then the first bin is ``[1, 2)`` (including 1, but excluding 2) and the
#second ``[2, 3)``.  The last bin, however, is ``[3, 4]``, which *includes*
#4.
#```
#Therefore, what you actually should do is specify exactly what bin edges you want, and either include one beyond your last data point or shift the bin edges to the 0.5 intervals. For example:
#```
```

```python
np.histogram([0, 1, 2, 3], bins=range(5))
#Output
#(array([1, 1, 1, 1]), array([0, 1, 2, 3, 4]))
#```
#Bin Alignment Now let's apply this to the first example and see what it looks like:
#```
#import matplotlib.pyplot as plt
#import numpy as np
#
## Generate a random array of integers between 0-9
## data.min() will be 0 and data.max() will be 9 (not 10)
#data = np.random.randint(0, 10, 1000)
#
#plt.hist(data, bins=range(11)) # <- The only difference
#plt.xticks(range(10))
#plt.show()
#```
#Okay, great! However, we now effectively have left-aligned bins. What if we wanted center-aligned bins to better reflect the fact that these are unique values? The quick way is to just shift the bin edges:
#```
#import matplotlib.pyplot as plt
#import numpy as np
#
## Generate a random array of integers between 0-9
## data.min() will be 0 and data.max() will be 9 (not 10)
#data = np.random.randint(0, 10, 1000)
#
#bins = np.arange(11) - 0.5
#plt.hist(data, bins)
#plt.xticks(range(10))
#plt.xlim([-1, 10])
#
#plt.show()
#```
#Similarly for right-aligned bins, just shift by -1. Another approach For the particular case of unique integer values, there's another, more efficient approach we can take. If you're dealing with unique integer counts starting with 0, you're better off using numpy.bincount than using numpy.hist. For example:
#```
#import matplotlib.pyplot as plt
#import numpy as np
#
#data = np.random.randint(0, 10, 1000)
#counts = np.bincount(data)
#
## Switching to the OO-interface. You can do all of this with "plt" as well.
#fig, ax = plt.subplots()
#ax.bar(range(10), counts, width=1, align='center')
#ax.set(xticks=range(10), xlim=[-1, 10])
#
#plt.show()
#```
#There are two big advantages to this approach. One is speed. numpy.histogram (and therefore plt.hist) basically runs the data through numpy.digitize and then numpy.bincount. Because you're dealing with unique integer values, there's no need to take the numpy.digitize step. However, the bigger advantage is more control over display. If you'd prefer thinner rectangles, just use a smaller width:
#```
#import matplotlib.pyplot as plt
#import numpy as np
#
#data = np.random.randint(0, 10, 1000)
#counts = np.bincount(data)
#
## Switching to the OO-interface. You can do all of this with "plt" as well.
#fig, ax = plt.subplots()
#ax.bar(range(10), counts, width=0.8, align='center')
#ax.set(xticks=range(10), xlim=[-1, 10])
#
#plt.show()
#```
```


Question:
Python equivalent to 'hold on' in Matlab Is there an explicit equivalent command in Python's matplotlib for Matlab's hold on? I'm trying to plot all my graphs on the same axes. Some graphs are generated inside a for loop, and these are plotted separately from su and sl:
```
import numpy as np
import matplotlib.pyplot as plt

for i in np.arange(1,5):
    z = 68 + 4 * np.random.randn(50)
    zm = np.cumsum(z) / range(1,len(z)+1)
    plt.plot(zm)
    plt.axis([0,50,60,80])

plt.show()

n = np.arange(1,51)
su = 68 + 4 / np.sqrt(n)
sl = 68 - 4 / np.sqrt(n)

plt.plot(n,su,n,sl)

plt.axis([0,50,60,80])
plt.show()
```

Response:
Just call plt.show() at the end:
```
import numpy as np
import matplotlib.pyplot as plt

plt.axis([0,50,60,80])
for i in np.arange(1,5):
    z = 68 + 4 * np.random.randn(50)
    zm = np.cumsum(z) / range(1,len(z)+1)
    plt.plot(zm)

n = np.arange(1,51)
su = 68 + 4 / np.sqrt(n)
sl = 68 - 4 / np.sqrt(n)

plt.plot(n,su,n,sl)

plt.show()
```


Question:
Using Colormaps to set color of line in matplotlib How does one set the color of a line in matplotlib with scalar values provided at run time using a colormap (say jet)? I tried a couple of different approaches here and I think I'm stumped. values[] is a storted array of scalars. curves are a set of 1-d arrays, and labels are an array of text strings. Each of the arrays have the same length.
```
fig = plt.figure()
ax = fig.add_subplot(111)
jet = colors.Colormap('jet')
cNorm  = colors.Normalize(vmin=0, vmax=values[-1])
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)
lines = []
for idx in range(len(curves)):
    line = curves[idx]
    colorVal = scalarMap.to_rgba(values[idx])
    retLine, = ax.plot(line, color=colorVal)
    #retLine.set_color()
    lines.append(retLine)
ax.legend(lines, labels, loc='upper right')
ax.grid()
plt.show()
```

Response:
The error you are receiving is due to how you define jet. You are creating the base class Colormap with the name 'jet', but this is very different from getting the default definition of the 'jet' colormap. This base class should never be created directly, and only the subclasses should be instantiated. What you've found with your example is a buggy behavior in Matplotlib. There should be a clearer error message generated when this code is run. This is an updated version of your example:
```
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
import numpy as np

# define some random data that emulates your indeded code:
NCURVES = 10
np.random.seed(101)
curves = [np.random.random(20) for i in range(NCURVES)]
values = range(NCURVES)

fig = plt.figure()
ax = fig.add_subplot(111)
# replace the next line
#jet = colors.Colormap('jet')
# with
jet = cm = plt.get_cmap('jet')
cNorm  = colors.Normalize(vmin=0, vmax=values[-1])
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)
print scalarMap.get_clim()

lines = []
for idx in range(len(curves)):
    line = curves[idx]
    colorVal = scalarMap.to_rgba(values[idx])
    colorText = (
        'color: (%4.2f,%4.2f,%4.2f)'%(colorVal[0],colorVal[1],colorVal[2])
        )
    retLine, = ax.plot(line,
                       color=colorVal,
                       label=colorText)
    lines.append(retLine)
#added this to get the legend to work
handles,labels = ax.get_legend_handles_labels()
ax.legend(handles, labels, loc='upper right')
ax.grid()
plt.show()
```
Resulting in: Using a ScalarMappable is an improvement over the approach presented in my related answer: creating over 20 unique legend colors using matplotlib


Question:
Plot an histogram with y-axis as percentage (using FuncFormatter?) I have a list of data in which the numbers are between 1000 and 20 000.
```
data = [1000, 1000, 5000, 3000, 4000, 16000, 2000]
```
When I plot a histogram using the hist() function, the y-axis represents the number of occurrences of the values within a bin. Instead of the number of occurrences, I would like to have the percentage of occurrences. Code for the above plot:
```
f, ax = plt.subplots(1, 1, figsize=(10,5))
ax.hist(data, bins = len(list(set(data))))
```
I've been looking at this post which describes an example using FuncFormatter but I can't figure out how to adapt it to my problem. Some help and guidance would be welcome :) EDIT: Main issue with the to_percent(y, position) function used by the FuncFormatter. The y corresponds to one given value on the y-axis I guess. I need to divide this value by the total number of elements which I apparently can' t pass to the function... EDIT 2: Current solution I dislike because of the use of a global variable:
```
def to_percent(y, position):
    # Ignore the passed in position. This has the effect of scaling the default
    # tick locations.
    global n

    s = str(round(100 * y / n, 3))
    print (y)

    # The percent symbol needs escaping in latex
    if matplotlib.rcParams['text.usetex'] is True:
        return s + r'$\%$'
    else:
        return s + '%'

def plotting_hist(folder, output):
    global n

    data = list()
    # Do stuff to create data from folder

    n = len(data)
    f, ax = plt.subplots(1, 1, figsize=(10,5))
    ax.hist(data, bins = len(list(set(data))), rwidth = 1)

    formatter = FuncFormatter(to_percent)
    plt.gca().yaxis.set_major_formatter(formatter)

    plt.savefig("{}.png".format(output), dpi=500)
```
EDIT 3: Method with density = True Actual desired output (method with global variable):

Response:
Other answers seem utterly complicated. A histogram which shows the proportion instead of the absolute amount can easily produced by weighting the data with 1/n, where n is the number of datapoints. Then a PercentFormatter can be used to show the proportion (e.g. 0.45) as percentage (45%).
```
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter

data = [1000, 1000, 5000, 3000, 4000, 16000, 2000]

plt.hist(data, weights=np.ones(len(data)) / len(data))

plt.gca().yaxis.set_major_formatter(PercentFormatter(1))
plt.show()
```
Here we see that three of the 7 values are in the first bin, i.e. 3/7=43%.


Question:
Does matplotlib have a function for drawing diagonal lines in axis coordinates? Matplotlib Axes have the functions axhline and axvline for drawing horizontal or vertical lines at a given y or x coordinate (respectively) independently of the data scale on an Axes. Is there a similar function for plotting a constant diagonal? For example, if I have a scatterplot of variables with a similar domain, it is often useful to know whether they fall above or below the line of y = x:
```
mean, cov = [0, 0], [(1, .6), (.6, 1)]
x, y = np.random.multivariate_normal(mean, cov, 100).T
y += x + 1
f, ax = plt.subplots(figsize=(6, 6))
ax.scatter(x, y, c=".3")
ax.plot([-3, 3], [-3, 3], ls="--", c=".3")
ax.set(xlim=(-3, 3), ylim=(-3, 3))
```
This can of course be done programmatically by grabbing the axis limits, (ax.get_xlim(), etc.), but that a) takes a few extra steps and b) is brittle in cases where more data might end up on the plot and shift the limits. (Actually in some cases just adding the constant line itself stretches the axes). It would be preferable to just do, e.g., ax.axdline(ls="--", c=".3"), but it's not clear if something like this exists in the matplotlib codebase. All you would need to do would be modify the axhline code to plot from [0, 1] in axes coordinates for both x and y, I think.

Response:
Drawing a diagonal from the lower left to the upper right corners of your plot would be accomplished by the following ax.plot([0, 1], [0, 1], transform=ax.transAxes) Using transform=ax.transAxes, the supplied x and y coordinates are interpreted as axes coordinates instead of data coordinates. This, as @fqq pointed out, is only the identity line when your x and y limits are equal. To draw the line y=x such that it always extends to the limits of your plot, an approach similar to the one given by @Ffisegydd would work, and can be written as the following function.
```
def add_identity(axes, *line_args, **line_kwargs):
    identity, = axes.plot([], [], *line_args, **line_kwargs)
    def callback(axes):
        low_x, high_x = axes.get_xlim()
        low_y, high_y = axes.get_ylim()
        low = max(low_x, low_y)
        high = min(high_x, high_y)
        identity.set_data([low, high], [low, high])
    callback(axes)
    axes.callbacks.connect('xlim_changed', callback)
    axes.callbacks.connect('ylim_changed', callback)
    return axes
```
Example usage:
```
import numpy as np
import matplotlib.pyplot as plt

mean, cov = [0, 0], [(1, .6), (.6, 1)]
x, y = np.random.multivariate_normal(mean, cov, 100).T
y += x + 1

f, ax = plt.subplots(figsize=(6, 6))
ax.scatter(x, y, c=".3")
add_identity(ax, color='r', ls='--')

plt.show()
```


Question: how to extract a subset of a colormap as a new colormap in matplotlib? I would like to use a colormap from matplotlib e.g. CMRmap. But I don't want to use the "black" color at the beginning and the "white" color at the end. I'm interested to plot my data using the in-between colors. I think ppl use it quite often but I was searching over internet and could not manage to find any simple solution. I'll appreciate if someone suggest any solution.

Response:
The staticmethod colors.LinearSegmentedColormap.from_list can be used to create new LinearSegmentedColormaps. Below, I sample the original colormap at 100 points between 0.2 and 0.8:
```
cmap(np.linspace(0.2, 0.8, 100))
```
and use these colors to generate a new colormap:
```
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np

def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):
    new_cmap = colors.LinearSegmentedColormap.from_list(
        'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval),
        cmap(np.linspace(minval, maxval, n)))
    return new_cmap

arr = np.linspace(0, 50, 100).reshape((10, 10))
fig, ax = plt.subplots(ncols=2)

cmap = plt.get_cmap('jet')
new_cmap = truncate_colormap(cmap, 0.2, 0.8)
ax[0].imshow(arr, interpolation='nearest', cmap=cmap)
ax[1].imshow(arr, interpolation='nearest', cmap=new_cmap)
plt.show()
```
The plot on the left shows the image using the original colormap (in this example, jet). The plot on the right shows the same image using new_cmap.


Question:
matplotlib iterate subplot axis array through single list Is there a simple/clean way to iterate an array of axis returned by subplots like
```
nrow = ncol = 2
a = []
fig, axs = plt.subplots(nrows=nrow, ncols=ncol)
for i, row in enumerate(axs):
    for j, ax in enumerate(row):
        a.append(ax)

for i, ax in enumerate(a):
    ax.set_ylabel(str(i))
```
which even works for nrow or ncol == 1. I tried list comprehension like:
```
[element for tupl in tupleOfTuples for element in tupl]
```
but that fails if nrows or ncols == 1

Response:
The ax return value is a numpy array, which can be reshaped, I believe, without any copying of the data. If you use the following, you'll get a linear array that you can iterate over cleanly.
```
nrow = 1; ncol = 2;
fig, axs = plt.subplots(nrows=nrow, ncols=ncol)

for ax in axs.reshape(-1):
  ax.set_ylabel(str(i))
```
This doesn't hold when ncols and nrows are both 1, since the return value is not an array; you could turn the return value into an array with one element for consistency, though it feels a bit like a cludge:
```
nrow = 1; ncol = 1;
fig, axs = plt.subplots(nrows=nrow, ncols=nrow)
axs = np.array(axs)

for ax in axs.reshape(-1):
  ax.set_ylabel(str(i))
```
reshape docs. The argument -1 causes reshape to infer dimensions of the output.


Question:
How do I plot list of tuples? I have the following data set. I would like to use Python or Gnuplot to plot the data. The tuples are of the form (x, y). The Y-axis should be a log axis, that is, log(y). A scatter plot or line plot would be ideal. How can this be done?
```
[(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),
 (2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),
 (4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]
```

Response:
If I get your question correctly, you could do something like this.
```

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

```python
testList =[(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),
#Output
# (2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),
# (4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]
```

```python
from math import log
```

```python
testList2 = [(elem1, log(elem2)) for elem1, elem2 in testList]
```

```python
testList2
#Output
#[(0, -16.617236475334405), (1, -17.67799605473062), (2, -18.691431541177973), (3, -18.9767093108359), (4, -19.420021520728017), (5, -19.298411635970396)]
```

```python
zip(*testList2)
#Output
#[(0, 1, 2, 3, 4, 5), (-16.617236475334405, -17.67799605473062, -18.691431541177973, -18.9767093108359, -19.420021520728017, -19.298411635970396)]
```

```python
plt.scatter(*zip(*testList2))
```

```python
plt.show()
#Output
#```
#which would give you something like Or as a line plot,
#```
```

```python
plt.plot(*zip(*testList2))
```

```python
plt.show()
#Output
#```
#EDIT - If you want to add a title and labels for the axis, you could do something like
#```
```

```python
plt.scatter(*zip(*testList2))
```

```python
plt.title('Random Figure')
```

```python
plt.xlabel('X-Axis')
```

```python
plt.ylabel('Y-Axis')
```

```python
plt.show()
#Output
#```
#which would give you
```


Question: How to map number to color using matplotlib's colormap? Consider a variable x containing a floating point number. I want to use matplotlib's colormaps to map this number to a color, but not plot anything. Basically, I want to be able to choose the colormap with mpl.cm.autumn for example, use mpl.colors.Normalize(vmin = -20, vmax = 10) to set the range, and then map x to the corresponding color. But I really don't get the documentation of mpl.cm, so if anyone could give me a hint.

Response:
It's as simple as cm.hot(0.3):
```py
import matplotlib.cm as cm

print(cm.hot(0.3))
```
```
(0.8240081481370484, 0.0, 0.0, 1.0)
```
If you also want to have the normalizer, use
```py
import matplotlib as mpl
import matplotlib.cm as cm

norm = mpl.colors.Normalize(vmin=-20, vmax=10)
cmap = cm.hot
x = 0.3

m = cm.ScalarMappable(norm=norm, cmap=cmap)
print(m.to_rgba(x))
```
```
(1.0, 0.8225486412996345, 0.0, 1.0)
```


Question: How to get matplotlib figure size For a project, I need to know the current size (in pixels) of my matplotlib figure, but I can't find how to do this. Does anyone know how to do this ?

Response:
```
import matplotlib.plt
fig = plt.figure()
size = fig.get_size_inches()*fig.dpi # size in pixels
```
To do it for the current figure,
```
fig = plt.gcf()
size = fig.get_size_inches()*fig.dpi # size in pixels
```
You can get the same info by doing:
```
bbox = fig.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
width, height = bbox.width*fig.dpi, bbox.height*fig.dpi
```


Question:
How to set the default color cycle for all subplots with matplotlib? How can I set a default set of colors for plots made with matplotlib? I can set a particular color map like this
```
import numpy as np
import matplotlib.pyplot as plt

fig=plt.figure(i)
ax=plt.gca()
colormap = plt.get_cmap('jet')
ax.set_color_cycle([colormap(k) for k in np.linspace(0, 1, 10)])
```
but is there some way to set the same set of colors for all plots, including subplots?

Response:
Sure! Either specify axes.color_cycle in your .matplotlibrc file or set it at runtime using matplotlib.rcParams or matplotlib.rc. As an example of the latter:
```py
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

# Set the default color cycle
mpl.rcParams['axes.prop_cycle'] = mpl.cycler(color=["r", "k", "c"])

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

fig, axes = plt.subplots(nrows=2)

for i in range(10):
    axes[0].plot(x, i * (x - 10)**2)

for i in range(10):
    axes[1].plot(x, i * np.cos(x))

plt.show()
```


Question:
How do I assign multiple legend labels at once? I have the following dataset:
```
x = [0, 1, 2, 3, 4]
y = [ [0, 1, 2, 3, 4],
      [5, 6, 7, 8, 9],
      [9, 8, 7, 6, 5] ]
```
Now I plot it with:
```
import matplotlib.pyplot as plt
plt.plot(x, y)
```
However, I want to label the 3 y-datasets with this command, which raises an error when .legend() is called:
```
lineObjects = plt.plot(x, y, label=['foo', 'bar', 'baz'])
plt.legend()

File "./plot_nmos.py", line 33, in <module>
  plt.legend()
...
AttributeError: 'list' object has no attribute 'startswith'
```
When I inspect the lineObjects:
```

```python
lineObjects[0].get_label()
#Output
#['foo', 'bar', 'baz']
```

```python
lineObjects[1].get_label()
#Output
#['foo', 'bar', 'baz']
```

```python
lineObjects[2].get_label()
#Output
#['foo', 'bar', 'baz']
#```
#Question Is there an elegant way to assign multiple labels by just using the .plot() method?
```

Response:
You can iterate over your line objects list, so labels are individually assigned. An example with the built-in python iter function:
```
lineObjects = plt.plot(x, y)
plt.legend(iter(lineObjects), ('foo', 'bar', 'baz'))`
```
Edit: after updating to matplotlib 1.1.1, it looks like the plt.plot(x, y), with y as a list of lists (as provided by the author of the question), doesn't work anymore. The one step plotting without iteration over the y arrays is still possible thought after passing y as numpy.array (assuming (numpy)[http://numpy.scipy.org/] as been previously imported). In this case, use plt.plot(x, y) (if the data in the 2D y array are arranged as columns [axis 1]) or plt.plot(x, y.transpose()) (if the data in the 2D y array are arranged as rows [axis 0]) Edit 2: as pointed by @pelson (see commentary below), the iter function is unnecessary and a simple plt.legend(lineObjects, ('foo', 'bar', 'baz')) works perfectly


Question:
Embedding small plots inside subplots in matplotlib If you want to insert a small plot inside a bigger one you can use Axes, like here. The problem is that I don't know how to do the same inside a subplot. I have several subplots and I would like to plot a small plot inside each subplot. The example code would be something like this:
```
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()

for i in range(4):
    ax = fig.add_subplot(2,2,i)
    ax.plot(np.arange(11),np.arange(11),'b')

    #b = ax.axes([0.7,0.7,0.2,0.2])
    #it gives an error, AxesSubplot is not callable

    #b = plt.axes([0.7,0.7,0.2,0.2])
    #plt.plot(np.arange(3),np.arange(3)+11,'g')
    #it plots the small plot in the selected position of the whole figure, not inside the subplot
```
Any ideas?

Response:
I wrote a function very similar to plt.axes. You could use it for plotting yours sub-subplots. There is an example...
```
import matplotlib.pyplot as plt
import numpy as np

#def add_subplot_axes(ax,rect,facecolor='w'): # matplotlib 2.0+
def add_subplot_axes(ax,rect,axisbg='w'):
    fig = plt.gcf()
    box = ax.get_position()
    width = box.width
    height = box.height
    inax_position  = ax.transAxes.transform(rect[0:2])
    transFigure = fig.transFigure.inverted()
    infig_position = transFigure.transform(inax_position)
    x = infig_position[0]
    y = infig_position[1]
    width *= rect[2]
    height *= rect[3]  # <= Typo was here
    #subax = fig.add_axes([x,y,width,height],facecolor=facecolor)  # matplotlib 2.0+
    subax = fig.add_axes([x,y,width,height],axisbg=axisbg)
    x_labelsize = subax.get_xticklabels()[0].get_size()
    y_labelsize = subax.get_yticklabels()[0].get_size()
    x_labelsize *= rect[2]**0.5
    y_labelsize *= rect[3]**0.5
    subax.xaxis.set_tick_params(labelsize=x_labelsize)
    subax.yaxis.set_tick_params(labelsize=y_labelsize)
    return subax

def example1():
    fig = plt.figure(figsize=(10,10))
    ax = fig.add_subplot(111)
    rect = [0.2,0.2,0.7,0.7]
    ax1 = add_subplot_axes(ax,rect)
    ax2 = add_subplot_axes(ax1,rect)
    ax3 = add_subplot_axes(ax2,rect)
    plt.show()

def example2():
    fig = plt.figure(figsize=(10,10))
    axes = []
    subpos = [0.2,0.6,0.3,0.3]
    x = np.linspace(-np.pi,np.pi)
    for i in range(4):
        axes.append(fig.add_subplot(2,2,i))
    for axis in axes:
        axis.set_xlim(-np.pi,np.pi)
        axis.set_ylim(-1,3)
        axis.plot(x,np.sin(x))
        subax1 = add_subplot_axes(axis,subpos)
        subax2 = add_subplot_axes(subax1,subpos)
        subax1.plot(x,np.sin(x))
        subax2.plot(x,np.sin(x))
if __name__ == '__main__':
    example2()
    plt.show()
```


Question:
Remove line through legend marker with .plot I have a matplotlib plot generated with the following code:
```
import matplotlib.pyplot as pyplot

Fig, ax = pyplot.subplots()
for i, (mark, color) in enumerate(zip(
    ['s', 'o', 'D', 'v'], ['r', 'g', 'b', 'purple'])):
    ax.plot(i+1, i+1, color=color,
            marker=mark,
            markerfacecolor='None',
            markeredgecolor=color,
            label=i)

ax.set_xlim(0,5)
ax.set_ylim(0,5)
ax.legend()
```
with this as the generated figure: I don't like the lines through the markers in the legend. How can I get rid of them?

Response:
You can specify linestyle='None' or linestyle='' as a keyword argument in the plot command. Also, ls= can replace linestyle=.
```py
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
for i, (mark, color) in enumerate(zip(
    ['s', 'o', 'D', 'v'], ['r', 'g', 'b', 'purple'])):
    ax.plot(i+1, i+1, color=color,
            marker=mark,
            markerfacecolor='None',
            markeredgecolor=color,
            linestyle='None',
            label=i)

ax.set_xlim(0, 5)
ax.set_ylim(0, 5)
ax.legend(numpoints=1)
plt.show()
```
Since you're only plotting single points, you can't see the line attribute except for in the legend.