Question:
Wrapping long y labels in matplotlib tight layout using setp I've been trying to wrap text for long labels in my code. I tried the textwrap method suggested earlier here, but my code defines yticklabels through an array imported from a csv using the pyplot.setp() method. I'm using tight_layout() for the formatting otherwise. So the question is - is there a way to wrap the really long y labels to newlines easily? Here is some sample code that I'd like a fix for:
```
import numpy as np
import matplotlib.pyplot as plt

labels=('Really really really really really really long label 1', 'Really really really really really really long label 2', 'Really really really really really really long label 3')
values=(30,50,40)

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

plt.ylim((0,40))
for i in np.arange(3):
    plt.barh(15*i, values[i])

plt.yticks(15*np.arange(3))
plt.setp(ax.set_yticklabels(labels))

plt.tight_layout()
plt.show()
```
This plots something like this I'd like the labels to go to newlines after a fixed width. Any ideas?

Response:
I have tried using textwrap on the labels and it works for me.
```
from textwrap import wrap
labels=['Really really really really really really long label 1',
        'Really really really really really really long label 2',
        'Really really really really really really long label 3']
labels = [ '\n'.join(wrap(l, 20)) for l in labels ]
```
Inserting this in your code gives us:


Question:
Remove colorbar from figure This should be easy but I'm having a hard time with it. Basically, I have a subplot in matplotlib that I'm drawing a hexbin plot in every time a function is called, but every time I call the function I get a new colorbar, so what I'd really like to do is update the colorbar. Unfortunately, this doesn't seem to work since the object the colorbar is attached to is being recreated by subplot.hexbin.
```
def foo(self):
   self.subplot.clear()
   hb = self.subplot.hexbin(...)
   if self.cb:
      self.cb.update_bruteforce() # Doesn't work (hb is new)
   else:
      self.cb = self.figure.colorbar(hb)
```
I'm now in this annoying place where I'm trying to delete the colorbar axes altogether and simply recreate it. Unfortunately, when I delete the colorbar axes, the subplot axes don't reclaim the space, and calling self.subplot.reset_position() isn't doing what I thought it would.
```
def foo(self):
   self.subplot.clear()
   hb = self.subplot.hexbin(...)
   if self.cb:
      self.figure.delaxes(self.figure.axes[1])
      del self.cb
      # TODO: resize self.subplot so it fills the
      #    whole figure before adding the new colorbar
   self.cb = self.figure.colorbar(hb)
```

Response:
I think the problem is that with del you cancel the variable, but not the referenced object colorbar. If you want the colorbar to be removed from plot and disappear, you have to use the method remove of the colorbar instance and to do this you need to have the colorbar in a variable, for which you have two options: holding the colorbar in a value at the moment of creation, as shown in other answers e.g. cb=plt.colorbar() retrieve an existing colorbar, that you can do following (and upvoting :)) what I wrote here: How to retrieve colorbar instance from figure in matplotlib then: cb.remove() plt.draw() #update plot Full code and result:
```
from matplotlib import pyplot as plt
import numpy as np

plt.ion()
plt.imshow(np.random.random(15).reshape((5,3)))
cb = plt.colorbar()
plt.savefig('test01.png')
cb.remove()
plt.savefig('test02.png')
```


Question:
How to obtain the same font(-style, -size etc.) in matplotlib output as in latex output? I have one .tex-document in which one graph is made by the python module matplotlib. What I want is, that the graph blends in to the document as good as possible. So I want the characters used in the graph to look exactly like the other same characters in the rest of the document. My first try looks like this (the matplotlibrc-file):
```
text.usetex   : True
text.latex.preamble: \usepackage{lmodern} #Used in .tex-document
font.size    : 11.0 #Same as in .tex-document
backend: PDF
```
For compiling of the .tex in which the PDF output of matplotlib is included, pdflatex is used. Now, the output looks not bad, but it looks somewhat different, the characters in the graph seem weaker in stroke width. What is the best approach for this? EDIT: Minimum example: LaTeX-Input:
```
\documentclass[11pt]{scrartcl}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}
\usepackage{graphicx}

\begin{document}

\begin{figure}
\includegraphics{./graph}
\caption{Excitation-Energy}
\label{fig:graph}
\end{figure}

\end{document}
```
Python-Script:
```
import matplotlib.pyplot as plt
import numpy as np

plt.plot([1,2,3,4])
plt.xlabel("Excitation-Energy")
plt.ylabel("Intensität")
plt.savefig("graph.pdf")
```
PDF output:

Response:
The difference in the fonts can be caused by incorrect parameter setting out pictures with matplotlib or wrong its integration into the final document. I think problem in text.latex.preamble: \usepackage{lmodern}. This thing works very badly and even developers do not guarantee its workability, how you can find here. In my case it did not work at all. Minimal differences in font associated with font family. For fix this u need: 'font.family' : 'lmodern' in rc. Other options and more detailed settings can be found here. To suppress this problem, I used a slightly different method - direct. plt.rcParams['text.latex.preamble']=[r"\usepackage{lmodern}"]. It is not strange, but it worked. Further information can be found at the link above. To prevent these effects suggest taking a look at this code:
```
import matplotlib.pyplot as plt

#Direct input
plt.rcParams['text.latex.preamble']=[r"\usepackage{lmodern}"]
#Options
params = {'text.usetex' : True,
          'font.size' : 11,
          'font.family' : 'lmodern',
          'text.latex.unicode': True,
          }
plt.rcParams.update(params)

fig = plt.figure()

#You must select the correct size of the plot in advance
fig.set_size_inches(3.54,3.54)

plt.plot([1,2,3,4])
plt.xlabel("Excitation-Energy")
plt.ylabel("Intensität")
plt.savefig("graph.pdf",
            #This is simple recomendation for publication plots
            dpi=1000,
            # Plot will be occupy a maximum of available space
            bbox_inches='tight',
            )
```
And finally move on to the latex:
```
\documentclass[11pt]{scrartcl}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}
\usepackage{graphicx}

\begin{document}

\begin{figure}
    \begin{center}
        \includegraphics{./graph}
        \caption{Excitation-Energy}
        \label{fig:graph}
    \end{center}
\end{figure}

\end{document}
```
Results As can be seen from a comparison of two fonts - differences do not exist (1 - MatPlotlib, 2 - pdfLaTeX)


Question:
Matplotlib - Border around scatter plot points I am following this tutorial. I would like to use Matplotlib to create a scatter plot with points that are colored inside, but have a black border, such as this plot: However, when I copy the code exactly, I get this plot instead. Here is the code:
```
colors = ['black', 'blue', 'purple', 'yellow', 'white', 'red', 'lime', 'cyan', 'orange', 'gray']
for i in range(len(colors)):
    x = reduced_data_rpca[:, 0][digits.target == i]
    y = reduced_data_rpca[:, 1][digits.target == i]
    plt.scatter(x, y, c=colors[i])
plt.legend(digits.target_names, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.xlabel('First Principal Component')
plt.ylabel('Second Principal Component')
plt.title("PCA Scatter Plot")
plt.show()
```
I tried adjusting the style, but that didn't help.

Response: When you use scatter plot, you set a color for both face and edge. In the official documentation you can find an additional parameter, edgecolors, which allows setting the edge color. edgecolors : color or sequence of color, optional, default: None If None, defaults to ‘face’ If ‘face’, the edge color will always be the same as the face color. If it is ‘none’, the patch boundary will not be drawn. For non-filled markers, the edgecolors kwarg is ignored and forced to ‘face’ internally. So, after all, you need only plt.scatter(x, y, c=colors[i],edgecolors='black')


Question: How to adjust space between legend markers and labels I want to adjust space between legend markers and labels. Sometime the space is too much as default. Does anyone know how to do this? Thanks.

Response:
legend() has a kwarg in called handletextpad which will do what you are looking for. By default, this is set to 0.8. From the docs: handletextpad : float or None The pad between the legend handle and text. Measured in font-size units. Default is None which will take the value from the legend.handletextpad rcParam. So when you call legend, add that kwarg, and experiment with the value. Something like:
```
ax.legend(handletextpad=0.1)
```
Consider the following:
```
import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(ncols=2)

ax1.plot(range(5), 'ro', label='handletextpad=0.8')
ax2.plot(range(5), 'bo', label='handletextpad=0.1')

ax1.legend()
ax2.legend(handletextpad=0.1)

plt.show()
```


Question:
How to set x axis values in matplotlib python? [duplicate] This question already has answers here: Modify tick label text (13 answers) Closed 2 years ago. I want to draw this graph using matplotlib. I wrote the code but it's not changing the x axis values.
```
import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.xlim(0.00001,5)
plt.ylim(0.8,1.4)
plt.plot(x, y, marker='o', linestyle='--', color='r',
label='Square')
plt.xlabel('x')
plt.ylabel('y')
plt.title('compare')
plt.legend()
plt.show()
```
How I can draw the blue line of the given graph using matplotlib?

Response:
The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:
```
import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square')
plt.xlabel('x')
plt.ylabel('y')
plt.xticks(xi, x)
plt.title('compare')
plt.legend()
plt.show()
```


Question: How to create a draggable legend in matplotlib? I'm drawing a legend on an axes object in matplotlib but the default positioning which claims to place it in a smart place doesn't seem to work. Ideally, I'd like to have the legend be draggable by the user. How can this be done?

Response:
Note: This is now built into matplotlib
```
leg = plt.legend()
if leg:
    leg.draggable()
```
will work as expected Well, I found bits and pieces of the solution scattered among mailing lists. I've come up with a nice modular chunk of code that you can drop in and use... here it is:
```
class DraggableLegend:
    def __init__(self, legend):
        self.legend = legend
        self.gotLegend = False
        legend.figure.canvas.mpl_connect('motion_notify_event', self.on_motion)
        legend.figure.canvas.mpl_connect('pick_event', self.on_pick)
        legend.figure.canvas.mpl_connect('button_release_event', self.on_release)
        legend.set_picker(self.my_legend_picker)

    def on_motion(self, evt):
        if self.gotLegend:
            dx = evt.x - self.mouse_x
            dy = evt.y - self.mouse_y
            loc_in_canvas = self.legend_x + dx, self.legend_y + dy
            loc_in_norm_axes = self.legend.parent.transAxes.inverted().transform_point(loc_in_canvas)
            self.legend._loc = tuple(loc_in_norm_axes)
            self.legend.figure.canvas.draw()

    def my_legend_picker(self, legend, evt):
        return self.legend.legendPatch.contains(evt)

    def on_pick(self, evt):
        if evt.artist == self.legend:
            bbox = self.legend.get_window_extent()
            self.mouse_x = evt.mouseevent.x
            self.mouse_y = evt.mouseevent.y
            self.legend_x = bbox.xmin
            self.legend_y = bbox.ymin
            self.gotLegend = 1

    def on_release(self, event):
        if self.gotLegend:
            self.gotLegend = False
```
...and in your code...
```
def draw(self):
    ax = self.figure.add_subplot(111)
    scatter = ax.scatter(np.random.randn(100), np.random.randn(100))

legend = DraggableLegend(ax.legend())
```
I emailed the Matplotlib-users group and John Hunter was kind enough to add my solution it to SVN HEAD. On Thu, Jan 28, 2010 at 3:02 PM, Adam Fraser wrote: I thought I'd share a solution to the draggable legend problem since it took me forever to assimilate all the scattered knowledge on the mailing lists... Cool -- nice example. I added the code to legend.py. Now you can do leg = ax.legend() leg.draggable() to enable draggable mode. You can repeatedly call this func to toggle the draggable state. I hope this is helpful to people working with matplotlib.


Question: matplotlib legend location numbers I am beginning to use Python for my scientific computing, and I am really liking it a lot, however I am confused by a feature of the matplotlib.pylab.legend function. In particular, the location feature allows one to specifiy the location of their legend using numbers, following this scheme: best -- 0 upper right -- 1 upper left -- 2 lower left -- 3 lower right -- 4 right -- 5 center left -- 6 center right -- 7 lower center -- 8 upper center -- 9 center -- 10 Does anyone know why you wouldn't use the ordering on the numpad? I.e. center -- 5, upper right -- 9, etc. I am just curious if anyone knows.

Response:
The docs show this example:
```
legend( ('label1', 'label2', 'label3'), loc='upper left')
```
Presumably, you could write loc=2, but why would you? It's much more readable to use the English word. As to why they didn't enumerate the values to align with the numeric keypad, I presume they weren't thinking about the numeric keypad at the time. Edit: It's worth including here the full text of Joe Kington's comment: Actually, they were deliberately mimicking matlab's behavior at the time. See the "obsolete location values" section in the documentation for MATLAB's legend: mathworks.com/help/techdoc/ref/legend.html


Question:
copy an axes content and show it in a new figure let say I have this code:
```
num_rows = 10
num_cols = 1
fig, axs = plt.subplots(num_rows, num_cols, sharex=True)
for i in xrange(num_rows):
     ax = axs[i]
     ax.plot(np.arange(10), np.arange(10)**i)
plt.show()
```
the result figure has too much info and now I want to pick 1 of the axes and draw it alone in a new figure I tried doing something like this
```
def on_click(event):
    axes = event.inaxes.get_axes()
    fig2 = plt.figure(15)
    fig2.axes.append(axes)
    fig2.show()

fig.canvas.mpl_connect('button_press_event', on_click)
```
but it didn't quite work. what would be the correct way to do it? searching through the docs and throw SE gave hardly any useful result edit: I don't mind redrawing the chosen axes, but I'm not sure how can I tell which of the axes was chosen so if that information is available somehow then it is a valid solution for me edit #2: so I've managed to do something like this:
```
def on_click(event):
    fig2 = plt.figure(15)
    fig2.clf()
    for line in event.inaxes.axes.get_lines():
         xydata = line.get_xydata()
         plt.plot(xydata[:, 0], xydata[:, 1])
    fig2.show()
```
which seems to be "working" (all the other information is lost - labels, lines colors, lines style, lines width, xlim, ylim, etc...) but I feel like there must be a nicer way to do it

Response:
Copying the axes The inital answer here does not work, we keep it for future reference and also to see why a more sophisticated approach is needed.
```css
#There are some pitfalls on the way with the initial approach.
#Adding an `axes` to a figure can be done via `fig.add_axes(axes)`. However, at this point,
#the axes' figure needs to be the figure the axes should be added to.
#This may sound a bit like running in circles but we can actually set the axes'
#figure as `axes.figure = fig2` and hence break out of this.

#One might then also position the axes in the new figure to take the usual dimensions.
#For this a dummy axes can be added first, the axes can change its position to the position
#of the dummy axes and then the dummy axes is removed again. In total, this would look as follows.

import matplotlib.pyplot as plt
import numpy as np

num_rows = 10
num_cols = 1
fig, axs = plt.subplots(num_rows, num_cols, sharex=True)
for i in xrange(num_rows):
     ax = axs[i]
     ax.plot(np.arange(10), np.arange(10)**i)

def on_click(event):
    axes = event.inaxes
    if not axes: return
    fig2 = plt.figure()
    axes.figure=fig2
    fig2.axes.append(axes)
    fig2.add_axes(axes)

    dummy = fig2.add_subplot(111)
    axes.set_position(dummy.get_position())
    dummy.remove()
    fig2.show()

fig.canvas.mpl_connect('button_press_event', on_click)

plt.show()

#So far so good, however, be aware that now after a click the axes is somehow
#residing in both figures, which can cause all sorts of problems, e.g. if you
# want to resize or save the initial figure.
```
Instead, the following will work: Pickling the figure The problem is that axes cannot be copied (even deepcopy will fail). Hence to obtain a true copy of an axes, you may need to use pickle. The following will work. It pickles the complete figure and removes all but the one axes to show.
```
import matplotlib.pyplot as plt
import numpy as np
import pickle
import io

num_rows = 10
num_cols = 1
fig, axs = plt.subplots(num_rows, num_cols, sharex=True)
for i in range(num_rows):
     ax = axs[i]
     ax.plot(np.arange(10), np.arange(10)**i)

def on_click(event):

    if not event.inaxes: return
    inx = list(fig.axes).index(event.inaxes)
    buf = io.BytesIO()
    pickle.dump(fig, buf)
    buf.seek(0)
    fig2 = pickle.load(buf)

    for i, ax in enumerate(fig2.axes):
        if i != inx:
            fig2.delaxes(ax)
        else:
            axes=ax

    axes.change_geometry(1,1,1)
    fig2.show()

fig.canvas.mpl_connect('button_press_event', on_click)

plt.show()
```
Recreate plots The alternative to the above is of course to recreate the plot in a new figure each time the axes is clicked. To this end one may use a function that creates a plot on a specified axes and with a specified index as input. Using this function during figure creation as well as later for replicating the plot in another figure ensures to have the same plot in all cases.
```
import matplotlib.pyplot as plt
import numpy as np

num_rows = 10
num_cols = 1
colors = plt.rcParams["axes.prop_cycle"].by_key()["color"]
labels = ["Label {}".format(i+1) for i in range(num_rows)]

def myplot(i, ax):
    ax.plot(np.arange(10), np.arange(10)**i, color=colors[i])
    ax.set_ylabel(labels[i])

fig, axs = plt.subplots(num_rows, num_cols, sharex=True)
for i in xrange(num_rows):
     myplot(i, axs[i])

def on_click(event):
    axes = event.inaxes
    if not axes: return
    inx = list(fig.axes).index(axes)
    fig2 = plt.figure()
    ax = fig2.add_subplot(111)
    myplot(inx, ax)
    fig2.show()

fig.canvas.mpl_connect('button_press_event', on_click)

plt.show()
```


Question:
Scientific notation colorbar I am trying to put a colorbar to my image using matplotlib. The issue comes when I try to force the ticklabels to be written in scientific notation. How can I force the scientific notation (ie, 1x10^0, 2x10^0, ..., 1x10^2, and so on) in the ticks of the color bar? Example, let's create and plot and image with its color bar:
```
import matplotlib as plot
import numpy as np

img = np.random.randn(300,300)
myplot = plt.imshow(img)
plt.colorbar(myplot)
plt.show()
```
When I do this, I get the following image: However, I would like to see the ticklabels in scientific notation... Is there any one line command to do this? Otherwise, is there any hint out there?

Response:
You could use colorbar's format parameter:
```
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.ticker as ticker

img = np.random.randn(300,300)
myplot = plt.imshow(img)

def fmt(x, pos):
    a, b = '{:.2e}'.format(x).split('e')
    b = int(b)
    return r'${} \times 10^{{{}}}$'.format(a, b)

plt.colorbar(myplot, format=ticker.FuncFormatter(fmt))
plt.show()
```


Question:
Logscale plots with zero values in matplotlib I am currently using logscale in order to have greater possibilities of plotting my data. Nevertheless, my data consists also of zero values. I know that these zero values will not work on logscale as log(0) is not defined. So e.g.,
```
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([0,1,2],[10,10,100],marker='o',linestyle='-')
ax.set_yscale('log')
ax.set_xscale('log')
```
completely omits the zero value. Is this behavior acceptable? At least there should be some kind of warning. I only recognized it by accident. Is there maybe also a way of plotting zero value data in logscale? Thanks! P.S.: I hope this fits to stackoverflow. I did not find a mailing list of matplotlib.

Response:
It's easiest to use a "symlog" plot for this purpose. The interval near 0 will be on a linear scale, so 0 can be displayed.
```
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([0,1,2],[10,10,100],marker='o',linestyle='-')
ax.set_yscale('symlog')
ax.set_xscale('symlog')
plt.show()
```
Symlog sets a small interval near zero (both above and below) to use a linear scale. This allows things to cross 0 without causing log(x) to explode (or go to -inf, rather). There's a nice visual comparison as an SO answer here: https://stackoverflow.com/a/3513150/325565


Question:
Scatter plot form dataframe with index on x-axis I've got pandas DataFrame, df, with index named date and the columns columnA, columnB and columnC I am trying to scatter plot index on a x-axis and columnA on a y-axis using the DataFrame syntax. When I try:
```
df.plot(kind='scatter', x='date', y='columnA')
```
I ma getting an error KeyError: 'date' probably because the date is not column
```
df.plot(kind='scatter', y='columnA')
```
I am getting an error:
```none
ValueError: scatter requires and x and y column
```
so no default index on x-axis.
```
df.plot(kind='scatter', x=df.index, y='columnA')
```
I am getting error
```none
KeyError: "DatetimeIndex(['1818-01-01', '1818-01-02', '1818-01-03', '1818-01-04',\n
                          '1818-01-05', '1818-01-06', '1818-01-07', '1818-01-08',\n
                          '1818-01-09', '1818-01-10',\n               ...\n
                          '2018-03-22', '2018-03-23', '2018-03-24', '2018-03-25',\n
                          '2018-03-26', '2018-03-27', '2018-03-28', '2018-03-29',\n
                          '2018-03-30', '2018-03-31'],\n
dtype='datetime64[ns]', name='date', length=73139, freq=None) not in index"
```
I can plot it if I use matplotlib.pyplot directly
```
plt.scatter(df.index, df['columnA'])
```
Is there a way to plot index as x-axis using the DataFrame kind syntax?

Response:
This is kind of ugly (I think the matplotlib solution you used in your question is better, FWIW), but you can always create a temporary DataFrame with the index as a column usinng
```
df.reset_index()
```
If the index was nameless, the default name will be 'index'. Assuming this is the case, you could use
```
df.reset_index().plot(kind='scatter', x='index', y='columnA')
```


Question: Is it possible to plot implicit equations? I would like to plot implicit equations (of the form f(x, y)=g(x, y) eg. X^y=y^x) in Matplotlib. Is this possible?

Response:
I don't believe there's very good support for this, but you could try something like
```
import matplotlib.pyplot
from numpy import arange
from numpy import meshgrid

delta = 0.025
xrange = arange(-5.0, 20.0, delta)
yrange = arange(-5.0, 20.0, delta)
X, Y = meshgrid(xrange,yrange)

# F is one side of the equation, G is the other
F = Y**X
G = X**Y

matplotlib.pyplot.contour(X, Y, (F - G), [0])
matplotlib.pyplot.show()
```
See the API docs for contour: if the fourth argument is a sequence then it specifies which contour lines to plot. But the plot will only be as good as the resolution of your ranges, and there are certain features it may never get right, often at self-intersection points.


Question: How to Display Custom Images in Tensorboard (e.g. Matplotlib Plots)? The Image Dashboard section of the Tensorboard ReadMe says: Since the image dashboard supports arbitrary pngs, you can use this to embed custom visualizations (e.g. matplotlib scatterplots) into TensorBoard. I see how a pyplot image could be written to file, read back in as a tensor, and then used with tf.image_summary() to write it to TensorBoard, but this statement from the readme suggests there is a more direct way. Is there? If so, is there any further documentation and/or examples of how to do this efficiently?

Response:
It is quite easy to do if you have the image in a memory buffer. Below, I show an example, where a pyplot is saved to a buffer and then converted to a TF image representation which is then sent to an image summary.
```
import io
import matplotlib.pyplot as plt
import tensorflow as tf

def gen_plot():
    """Create a pyplot plot and save to buffer."""
    plt.figure()
    plt.plot([1, 2])
    plt.title("test")
    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    buf.seek(0)
    return buf

# Prepare the plot
plot_buf = gen_plot()

# Convert PNG buffer to TF image
image = tf.image.decode_png(plot_buf.getvalue(), channels=4)

# Add the batch dimension
image = tf.expand_dims(image, 0)

# Add image summary
summary_op = tf.summary.image("plot", image)

# Session
with tf.Session() as sess:
    # Run
    summary = sess.run(summary_op)
    # Write summary
    writer = tf.train.SummaryWriter('./logs')
    writer.add_summary(summary)
    writer.close()
```
This gives the following TensorBoard visualization:


Question:
How to create a grouped bar plot The goal here is to create a grouped bar plot, not subplots like the image below Is there a simple way to create a grouped bar plot in Python? Right now I get separate bar plots, instead of separate bars on one plot.
```py
import pandas as pd

df = pd.DataFrame([['g1', 'c1', 10], ['g1', 'c2', 12], ['g1', 'c3', 13], ['g2', 'c1', 8], ['g2', 'c2', 10], ['g2', 'c3', 12]], columns=['group', 'column', 'val'])

  group column  val
0    g1     c1   10
1    g1     c2   12
2    g1     c3   13
3    g2     c1    8
4    g2     c2   10
5    g2     c3   12

df.groupby(['group']).plot(kind='bar')
```

Response:
Pandas will show grouped bars by columns. Entries in each row but different columns will constitute a group in the resulting plot. Hence you need to "reshape" your dataframe to have the "group" as columns. In this case you can pivot like
```
df.pivot("column", "group", "val")
```
producing
```
group   g1  g2
column
c1      10   8
c2      12  10
c3      13  12
```
Plotting this will result in a grouped bar chart.
```
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame([['g1','c1',10],['g1','c2',12],['g1','c3',13],['g2','c1',8],
                   ['g2','c2',10],['g2','c3',12]],columns=['group','column','val'])

df.pivot("column", "group", "val").plot(kind='bar')

plt.show()
```


Question: How to display all minor tick marks on a semi-log plot When making a semi-log plot (y is log), the minor tick marks (8 in a decade) on the y axis appear automatically, but it seems that when the axis range exceeds 10**10, they disappear. I tried many ways to force them back in, but to no avail. It might be that they go away for large ranges to avoid overcrowding, but one should have a choice?

Response:
solution for matplotlib >= 2.0.2 Let's consider the following example which is produced by this code:
```
import matplotlib.pyplot as plt
import matplotlib.ticker
import numpy as np

y = np.arange(12)
x = 10.0**y

fig, ax=plt.subplots()
ax.plot(x,y)
ax.set_xscale("log")
plt.show()
```
The minor ticklabels are indeed gone and usual ways to show them (like plt.tick_params(axis='x', which='minor')) fail. The first step would then be to show all powers of 10 on the axis,
```
locmaj = matplotlib.ticker.LogLocator(base=10,numticks=12)
ax.xaxis.set_major_locator(locmaj)
```
where the trick is to set numticks to a number equal or larger the number of ticks (i.e. 12 or higher in this case). Then, we can add minor ticklabels as
```
locmin = matplotlib.ticker.LogLocator(base=10.0,subs=(0.2,0.4,0.6,0.8),numticks=12)
ax.xaxis.set_minor_locator(locmin)
ax.xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())
```
Note that I restricted this to include 4 minor ticks per decade (using 8 is equally possible but in this example would overcrowd the axes). Also note that numticks is again (quite unintuitively) 12 or larger. Finally we need to use a NullFormatter() for the minor ticks, in order not to have any ticklabels appear for them. solution for matplotlib 2.0.0 The following works in matplotlib 2.0.0 or below, but it does not work in matplotlib 2.0.2. Let's consider the following example which is produced by this code:
```
import matplotlib.pyplot as plt
import matplotlib.ticker
import numpy as np

y = np.arange(12)
x = 10.0**y

fig, ax=plt.subplots()
ax.plot(x,y)
ax.set_xscale("log")
plt.show()
```
The minor ticklabels are indeed gone and usual ways to show them (like plt.tick_params(axis='x', which='minor')) fail. The first step would then be to show all powers of 10 on the axis,
```
locmaj = matplotlib.ticker.LogLocator(base=10.0, subs=(0.1,1.0, ))
ax.xaxis.set_major_locator(locmaj)
```
Then, we can add minor ticklabels as
```
locmin = matplotlib.ticker.LogLocator(base=10.0, subs=(0.1,0.2,0.4,0.6,0.8,1,2,4,6,8,10 ))
ax.xaxis.set_minor_locator(locmin)
ax.xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())
```
Note that I restricted this to include 4 minor ticks per decade (using 8 is equally possible but in this example would overcrowd the axes). Also note - and that may be the key here - that the subs argument, which gives the multiples of integer powers of the base at which to place ticks (see documentation), is given a list ranging over two decades instead of one. Finally we need to use a NullFormatter() for the minor ticks, in order not to have any ticklabels appear for them.


Question: How to plot 1-d data at given y-value with pylab I want to plot the data points that are in a 1-D array just along the horizontal axis [edit: at a given y-value], like in this plot: How can I do this with pylab?

Response:
Staven already edited his post to include how to plot the values along y-value 1, but he was using Python lists. A variant that should be faster (although I did not measure it) only uses numpy arrays:
```
import numpy as np
import matplotlib.pyplot as pp
val = 0. # this is the value where you want the data to appear on the y-axis.
ar = np.arange(10) # just as an example array
pp.plot(ar, np.zeros_like(ar) + val, 'x')
pp.show()
```
As a nice-to-use function that offers all usual matplotlib refinements via kwargs this would be:
```
def plot_at_y(arr, val, **kwargs):
    pp.plot(arr, np.zeros_like(arr) + val, 'x', **kwargs)
    pp.show()
```


Question:
Matplotlib histogram with collection bin for high values I have an array with values, and I want to create a histogram of it. I am mainly interested in the low end numbers, and want to collect every number above 300 in one bin. This bin should have the same width as all other (equally wide) bins. How can I do this? Note: this question is related to this question: Defining bin width/x-axis scale in Matplotlib histogram This is what I tried so far:
```
import matplotlib.pyplot as plt
import numpy as np

def plot_histogram_01():
    np.random.seed(1)
    values_A = np.random.choice(np.arange(600), size=200, replace=True).tolist()
    values_B = np.random.choice(np.arange(600), size=200, replace=True).tolist()

    bins = [0, 25, 50, 75, 100, 125, 150, 175, 200, 225, 250, 275, 300, 600]

    fig, ax = plt.subplots(figsize=(9, 5))
    _, bins, patches = plt.hist([values_A, values_B], normed=1,  # normed is deprecated and will be replaced by density
                                bins=bins,
                                color=['#3782CC', '#AFD5FA'],
                                label=['A', 'B'])

    xlabels = np.array(bins[1:], dtype='|S4')
    xlabels[-1] = '300+'

    N_labels = len(xlabels)
    plt.xlim([0, 600])
    plt.xticks(25 * np.arange(N_labels) + 12.5)
    ax.set_xticklabels(xlabels)

    plt.yticks([])
    plt.title('')
    plt.setp(patches, linewidth=0)
    plt.legend()

    fig.tight_layout()
    plt.savefig('my_plot_01.png')
    plt.close()
```
This is the result, which does not look nice: I then changed the line with xlim in it:
```
plt.xlim([0, 325])
```
With the following result: It looks more or less as I want it, but the last bin is not visible now. Which trick am I missing to visualize this last bin with a width of 25?

Response:
Numpy has a handy function for dealing with this: np.clip. Despite what the name may sound like, it doesn't remove values, it just limits them to the range you specify. Basically, it does Artem's "dirty hack" inline. You can leave the values as they are, but in the hist call, just wrap the array in an np.clip call, like so
```
plt.hist(np.clip(values_A, bins[0], bins[-1]), bins=bins)
```
This is nicer for a number of reasons: It's way faster — at least for large numbers of elements. Numpy does its work at the C level. Operating on python lists (as in Artem's list comprehension) has a lot of overhead for each element. Basically, if you ever have the option to use numpy, you should. You do it right where it's needed, which reduces the chance of making mistakes in your code. You don't need to keep a second copy of the array hanging around, which reduces memory usage (except within this one line) and further reduces the chances of making mistakes. Using bins[0], bins[-1] instead of hard-coding the values reduces the chances of making mistakes again, because you can change the bins just where bins was defined; you don't need to remember to change them in the call to clip or anywhere else. So to put it all together as in the OP:
```
import matplotlib.pyplot as plt
import numpy as np

def plot_histogram_01():
    np.random.seed(1)
    values_A = np.random.choice(np.arange(600), size=200, replace=True)
    values_B = np.random.choice(np.arange(600), size=200, replace=True)

    bins = np.arange(0,350,25)

    fig, ax = plt.subplots(figsize=(9, 5))
    _, bins, patches = plt.hist([np.clip(values_A, bins[0], bins[-1]),
                                 np.clip(values_B, bins[0], bins[-1])],
                                # normed=1,  # normed is deprecated; replace with density
                                density=True,
                                bins=bins, color=['#3782CC', '#AFD5FA'], label=['A', 'B'])

    xlabels = bins[1:].astype(int).astype(str)
    xlabels[-1] += '+'

    N_labels = len(xlabels)
    plt.xlim([0, 325])
    plt.xticks(25 * np.arange(N_labels) + 12.5)
    ax.set_xticklabels(xlabels)

    plt.yticks([])
    plt.title('')
    plt.setp(patches, linewidth=0)
    plt.legend(loc='upper left')

    fig.tight_layout()
plot_histogram_01()
```


Question: Understanding matplotlib: plt, figure, ax(arr)? I'm not really new to matplotlib and I'm deeply ashamed to admit I have always used it as a tool for getting a solution as quick and easy as possible. So I know how to get basic plots, subplots and stuff and have quite a few code which gets reused from time to time...but I have no "deep(er) knowledge" of matplotlib. Recently I thought I should change this and work myself through some tutorials. However, I am still confused about matplotlibs plt, fig(ure) and ax(arr). What is really the difference? In most cases, for some "quick'n'dirty' plotting I see people using just pyplot as plt and directly plot with plt.plot. Since I am having multiple stuff to plot quite often, I frequently use f, axarr = plt.subplots()...but most times you see only code putting data into the axarr and ignoring the figure f. So, my question is: what is a clean way to work with matplotlib? When to use plt only, what is or what should a figure be used for? Should subplots just containing data? Or is it valid and good practice to everything like styling, clearing a plot, ..., inside of subplots? I hope this is not to wide-ranging. Basically I am asking for some advice for the true purposes of plt  fig  ax(arr) (and when/how to use them properly). Tutorials would also be welcome. The matplotlib documentation is rather confusing to me. When one searches something really specific, like rescaling a legend, different plot markers and colors and so on the official documentation is really precise but rather general information is not that good in my opinion. Too much different examples, no real explanations of the purposes...looks more or less like a big listing of all possible API methods and arguments.

Response: pyplot is the 'scripting' level API in matplotlib (its highest level API to do a lot with matplotlib). It allows you to use matplotlib using a procedural interface in a similar way as you can do it with Matlab. pyplot has a notion of 'current figure' and 'current axes' that all the functions delegate to (@tacaswell dixit). So, when you use the functions available on the module pyplot you are plotting to the 'current figure' and 'current axes'. If you want 'fine-grain' control of where/what your are plotting then you should use an object oriented API using instances of Figure and Axes. Functions available in pyplot have an equivalent method in the Axes. From the repo anatomy of matplotlib: The Figure is the top-level container in this hierarchy. It is the overall window/page that everything is drawn on. You can have multiple independent figures and Figures can contain multiple Axes. But... Most plotting occurs on an Axes. The axes is effectively the area that we plot data on and any ticks/labels/etc associated with it. Usually we'll set up an Axes with a call to subplot (which places Axes on a regular grid), so in most cases, Axes and Subplot are synonymous. Each Axes has an XAxis and a YAxis. These contain the ticks, tick locations, labels, etc. If you want to know the anatomy of a plot you can visit this link.


Question:
How to center labels in histogram plot I have a numpy array results that looks like
```
[ 0.  2.  0.  0.  0.  0.  3.  0.  0.  0.  0.  0.  0.  0.  0.  2.  0.  0.
  0.  0.  0.  1.  0.  0.  0.  0.  0.  0.  0.  1.  0.  0.  0.  0.  0.  0.
  0.  1.  1.  0.  0.  0.  0.  2.  0.  3.  1.  0.  0.  2.  2.  0.  0.  0.
  0.  0.  0.  0.  0.  1.  1.  0.  0.  0.  0.  0.  0.  2.  0.  0.  0.  0.
  0.  1.  0.  0.  0.  0.  0.  0.  0.  0.  0.  3.  1.  0.  0.  0.  0.  0.
  0.  0.  0.  1.  0.  0.  0.  1.  2.  2.]
```
I would like to plot a histogram of it. I have tried
```
import matplotlib.pyplot as plt
plt.hist(results, bins=range(5))
plt.show()
```
This gives me a histogram with the x-axis labelled 0.0 0.5 1.0 1.5 2.0 2.5 3.0. 3.5 4.0. I would like the x-axis to be labelled 0 1 2 3 instead with the labels in the center of each bar. How can you do that?

Response:
The other answers just don't do it for me. The benefit of using plt.bar over plt.hist is that bar can use align='center':
```
import numpy as np
import matplotlib.pyplot as plt

arr = np.array([ 0.,  2.,  0.,  0.,  0.,  0.,  3.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.,  2.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  1.,
        0.,  0.,  0.,  0.,  2.,  0.,  3.,  1.,  0.,  0.,  2.,  2.,  0.,
        0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  1.,  0.,  0.,  0.,  0.,
        0.,  0.,  2.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  0.,  0.,  3.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.,  1.,  0.,  0.,  0.,  1.,  2.,  2.])

labels, counts = np.unique(arr, return_counts=True)
plt.bar(labels, counts, align='center')
plt.gca().set_xticks(labels)
plt.show()
```


Question:
matplotlib ticks thickness Is there a way to increase the thickness and size of ticks in matplotlib without having to write a long piece of code like this:
```
for line in ax1.yaxis.get_ticklines():
    line.set_markersize(25)
    line.set_markeredgewidth(3)
```
The problem with this piece of code is that it uses a loop which costs usually a lot of CPU usage.

Response:
A simpler way is to use the set_tick_params function of axis objects:
```
ax.xaxis.set_tick_params(width=5)
ax.yaxis.set_tick_params(width=5)
```
Doing it this way means you can change this on a per-axis basis with out worrying about global state and with out making any assumptions about the internal structure of mpl objects. If you want to set this for all the ticks in your axes,
```
ax = plt.gca()
ax.tick_params(width=5,...)
```
Take a look at set_tick_params doc and tick_params valid keywords


Question:
pyplot zooming in I am trying to plot some data from Flexible Image Transport System (FITS) files, and I wanted to know if anyone knows how to focus on certain regions of a plot's axis. Here is some example code:
```py
import pyfits
from matplotlib import pyplot as plt
from matplotlib import pylab
from pylab import *
#Assuming I have my data in the current directory
a = pyfits.getdata('fits1.fits')
x = a['data1'] # Let's assume data1 is the column: [0, 1, 1.3, 1.5, 2, 4,  8]
y = a['data2'] # And data2 is the column:          [0, 0.5, 1, 1.5, 2, 2.5,3]
plt.plot(x,y)
```
How could I only plot the region from [1.3 to 4] in the x-axis?

Response:
Use the plt.axis() function with your limits.
```
plt.axis([x_min, x_max, y_min, y_max])
```
where x_min, x_max, y_min, and y_max are the coordinate limits for both axes.


Question:
Bar Chart: How to choose color if value is positive vs value is negative I have a pandas dataframe with positive and negative values and want to plot it as a bar chart. I want to plot the positive colors 'green' and the negative values 'red' (very original...lol). I'm not sure how to pass if > 0 'green' else < 0 'red'?
```
data = pd.DataFrame([[-15], [10], [8], [-4.5]],
                    index=['a', 'b', 'c', 'd'],
                    columns=['values'])
data.plot(kind='barh')
```

Response:
I would create a dummy column for whether the observation is larger than 0.
```

```python
data['positive'] = data['values'] > 0
```

```python
data
#Output
#values positive
#a   -15.0    False
#b    10.0     True
#c     8.0     True
#d    -4.5    False
#
#[4 rows x 2 columns]
```

```python
data['values'].plot(kind='barh',
                             color=data.positive.map({True: 'g', False: 'r'}))
```
Also, you may want to be careful not to have column names that overlap with DataFrame attributes. DataFrame.values give the underlying numpy array for a DataFrame. Having overlapping names prevents you from using the df. syntax.
```


Question:
Running infinite loops using threads in python My program is designed in the following way: First part of the program takes real time values from a sensor and plots it using Matplotlib. This has to be done for long durations. And also, it logs information into a database. The second part is the IP Camera. I have to get the input from an IP Camera and display it. For displaying I am using OpenCV's imshow method. Also, I am storing the video from the IP Camera. Question: I have the algorithms in place, the problem is I need to run both these in a while loops. The condition is that I cannot exit from any of them. Now threading is a good alternative for this but I have read about the GIL, so how do I go about running two infinite loops?
```
from multiprocessing import Process

def methodA():
    while TRUE:
        do something

def methodB():
    while TRUE:
        do something

p=Process(target=methodA())
p.start()
p1=Process(target=methodB())
p1.start()
```
Now when I start process p it starts executing, after that how do I start p1 to run simultaneously?

Response:
As far as I understood your question, you have two different tasks that you want them to perform continuously. Now regarding your questions: how do I go about running two infinite loops? You can create two different threads that will run these infinite loops for you. The first thread will perform your task1 and second one will perform task2. Also, once I start executing a thread, how do I execute the other thread when the first thread is running continuously/infinitely? If you are using two different threads then you don't need to be worried about this issue. If the threads are not sharing any resource then you don't need to worry about this fact. How ever if you want to stop/pause one thread from the other thread or vice versa then you can implement a mechanism using flags or locks. These questions will help in this case: Is there any way to kill a Thread in Python? Why does the python threading.Thread object has 'start', but not 'stop'? making-a-program-munltithreaded Sample example using threading:
```
from threading import Thread

class myClassA(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.daemon = True
        self.start()
    def run(self):
        while True:
            print 'A'

class myClassB(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.daemon = True
        self.start()
    def run(self):
        while True:
            print 'B'

myClassA()
myClassB()
while True:
    pass
```
For shared resources? Use Locks for them. Here are some examples. One, two and How to synchronize threads in python? what if I don't want to run it using classes? How do I do this using only methods?
```
from threading import Thread

def runA():
    while True:
        print 'A\n'

def runB():
    while True:
        print 'B\n'

if __name__ == "__main__":
    t1 = Thread(target = runA)
    t2 = Thread(target = runB)
    t1.setDaemon(True)
    t2.setDaemon(True)
    t1.start()
    t2.start()
    while True:
        pass
```


Question:
Superimpose scatter plots I am using Python matplotlib. i want to superimpose scatter plots. I know how to superimpose continuous line plots with commands:
```

```python
plt.plot(seriesX)
```

```python
plt.plot(Xresampl)
```

```python
plt.show()
#Output
#```
#But it does not seem to work the same way with scatter. Or maybe using plot() with a further argument specifying line style. How to proceed? thanks
```

Response:
You simply call the scatter function twice, matplotlib will superimpose the two plots for you. You might want to specify a color, as the default for all scatter plots is blue. This is perhaps why you were only seeing one plot.
```
import numpy as np
import pylab as plt

X = np.linspace(0,5,100)
Y1 = X + 2*np.random.random(X.shape)
Y2 = X**2 + np.random.random(X.shape)

plt.scatter(X,Y1,color='k')
plt.scatter(X,Y2,color='g')
plt.show()
```


Question:
Overlapping y-axis tick label and x-axis tick label in matplotlib If I create a plot with matplotlib using the following code:
```
import numpy as np
from matplotlib import pyplot as plt
xx = np.arange(0,5, .5)
yy = np.random.random( len(xx) )
plt.plot(xx,yy)
plt.imshow()
```
I get a result that looks like the attached image. The problem is the bottom-most y-tick label overlaps the left-most x-tick label. This looks unprofessional. I was wondering if there was an automatic way to delete the bottom-most y-tick label, so I don't have the overlap problem. The fewer lines of code, the better.

Response:
In the ticker module there is a class called MaxNLocator that can take a prune kwarg. Using that you can remove the first tick:
```
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
import numpy as np
xx = np.arange(0,5, .5)
yy = np.random.random( len(xx) )
plt.plot(xx,yy)
plt.gca().xaxis.set_major_locator(MaxNLocator(prune='lower'))
plt.show()
```
Result:


Question:
Drawing rectangle with border only in matplotlib So I found the following code here:
```
from matplotlib import pyplot as plt
from matplotlib.patches import Rectangle
someX, someY = 0.5, 0.5
plt.figure()
currentAxis = plt.gca()
currentAxis.add_patch(Rectangle((someX - .1, someY - .1), 0.2, 0.2,alpha=1))
plt.show()
```
Which gives: But what I want is a rectangle with only a blue border and inside of it to be transparent. How can I do this?

Response:
You just need to set the facecolor to the string 'none' (not the python None)
```
from matplotlib import pyplot as plt
from matplotlib.patches import Rectangle
someX, someY = 0.5, 0.5
fig,ax = plt.subplots()
currentAxis = plt.gca()
currentAxis.add_patch(Rectangle((someX - 0.1, someY - 0.1), 0.2, 0.2,
                      alpha=1, facecolor='none'))
```


Question:
Overcome ValueError for empty array In this discussion I tried to fix an issue in plotting limits for y-axis, after the twiny() messes up my plot. I thought this:
```
ax.set_ylim([y.min()-0.05, y.max()+0.05])
```
was a good solution. And probably it is, for continuous set of data. As I said in that discussion, anyway, my data are noisy, and sometimes with gaps. So it happens that some plotted ranges have no data. In that case, naturally, the use of the .min() raises the error:
```
ValueError: zero-size array to reduction operation minimum which has no identity
```
because the array is empty. How to work around it, so that the code just does not care about putting limits on the y-axis? (Hoping that this is the only issue the empty array will cause)

Response:
Just catch the exception and ignore it:
```
try:
    ax.set_ylim([y.min()-0.05, y.max()+0.05])
except ValueError:  #raised if `y` is empty.
    pass
```


Question: Suggestions to plot overlapping lines in matplotlib? Does anybody have a suggestion on what's the best way to present overlapping lines on a plot? I have a lot of them, and I had the idea of having full lines of different colors where they don't overlap, and having dashed lines where they do overlap so that all colors are visible and overlapping colors are seen. But still, how do I that.

Response:
I have the same issue on a plot with a high degree of discretization. Here the starting situation:
```
import matplotlib.pyplot as plt
grid=[x for x in range(10)]
graphs=[
        [1,1,1,4,4,4,3,5,6,0],
        [1,1,1,5,5,5,3,5,6,0],
        [1,1,1,0,0,3,3,2,4,0],
        [1,2,4,4,3,2,3,2,4,0],
        [1,2,3,3,4,4,3,2,6,0],
        [1,1,3,3,0,3,3,5,4,3],
        ]

for gg,graph in enumerate(graphs):
    plt.plot(grid,graph,label='g'+str(gg))

plt.legend(loc=3,bbox_to_anchor=(1,0))
plt.show()
```
No one can say where the green and blue lines run exactly and my "solution"
```
import matplotlib.pyplot as plt
grid=[x for x in range(10)]
graphs=[
        [1,1,1,4,4,4,3,5,6,0],
        [1,1,1,5,5,5,3,5,6,0],
        [1,1,1,0,0,3,3,2,4,0],
        [1,2,4,4,3,2,3,2,4,0],
        [1,2,3,3,4,4,3,2,6,0],
        [1,1,3,3,0,3,3,5,4,3],
        ]

for gg,graph in enumerate(graphs):
    lw=10-8*gg/len(graphs)
    ls=['-','--','-.',':'][gg%4]
    plt.plot(grid,graph,label='g'+str(gg), linestyle=ls, linewidth=lw)

plt.legend(loc=3,bbox_to_anchor=(1,0))
plt.show()
```
I am grateful for suggestions on improvement!


Question:
Manipulation on vertical space in matplotlib subplots I want to reduce the verticalspacing between subplot. Surfing along the web I just have found how to reduce the horizontal spacing, something like
```
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=4, ncols=4)
fig.tight_layout() # Or equivalently,  "plt.tight_layout()"
fig.subplots_adjust(hspace=0.5)
plt.show()
```
The hspace thing is the one that manipulates such behaviour, but apparently there's no vspace. EDIT: This does not reduce the space between the y-axis, that is what I want to manipulate.

Response:
As you said in your question hspace reduces the vertical spacing between subplots. The equivalent for horizontal spacing between subplots is wspace. Below is an example:
```
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

fig, ((ax1,ax2),(ax3,ax4)) = plt.subplots(nrows=2, ncols=2)
fig.tight_layout()
ax1.plot(x, y)
ax2.scatter(x, y)
ax3.scatter(x, y)
ax4.scatter(x, y)

fig.subplots_adjust(wspace=0.2)
plt.show()
```
Using a value for 1 for wspace gives Using 0.2 as the value of wspace gives


Question: python matplotlib dash-dot-dot - how to? I am using python and matplotlib to generate graphical output. Is there a simple way to generate a dash-dot-dot line-style? I am aware of the '--', '-.', and ':' options. Unfortunately, '-..' does not result in a dash-dot-dot line. I have looked at the set_dashes command, but that seems to control the length of the dashes and the space between two adjacent dashes. One option may be to plot two lines on top of each other; one dashed with ample space between the dashes - and one dotted, with the dots as large as the dashes are wide and spaced so that two dots are in between each of the dashes. I do not doubt this can be done, I am simply hoping for an easier way. Did I overlook an option?

Response:
You can define custom dashes:
```
import matplotlib.pyplot as plt

line, = plt.plot([1,5,2,4], '-')
line.set_dashes([8, 4, 2, 4, 2, 4])
plt.show()
```
[8, 4, 2, 4, 2, 4] means 8 points on, (dash) 4 points off, 2 points on, (dot) 4 points off, 2 points on, (dot) 4 points off. @Achim noted you can also specify the dashes parameter:
```
plt.plot([1,5,2,4], '-', dashes=[8, 4, 2, 4, 2, 4])
plt.show()
```
produces the same result shown above.


Question: Plotting results of Pandas GroupBy I'm starting to learn Pandas and am trying to find the most Pythonic (or panda-thonic?) ways to do certain tasks. Suppose we have a DataFrame with columns A, B, and C. Column A contains boolean values: each row's A value is either true or false. Column B has some important values we want to plot. What we want to discover is the subtle distinctions between B values for rows that have A set to false, vs. B values for rows that have A is true. In other words, how can I group by the value of column A (either true or false), then plot the values of column B for both groups on the same graph? The two datasets should be colored differently to be able to distinguish the points. Next, let's add another feature to this program: before graphing, we want to compute another value for each row and store it in column D. This value is the mean of all data stored in B for the entire five minutes before a record - but we only include rows that have the same boolean value stored in A. In other words, if I have a row where A=True and time=t, I want to compute a value for column D that is the mean of B for all records from time t-5 to t that have the same A=True. In this case, how can we execute the groupby on values of A, then apply this computation to each individual group, and finally plot the D values for the two groups?

Response:
I think @herrfz hit all the high points. I'll just flesh out the details:
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

sin = np.sin
cos = np.cos
pi = np.pi
N = 100

x = np.linspace(0, pi, N)
a = sin(x)
b = cos(x)

df = pd.DataFrame({
    'A': [True]*N + [False]*N,
    'B': np.hstack((a,b))
    })

for key, grp in df.groupby(['A']):
    plt.plot(grp['B'], label=key)
    grp['D'] = pd.rolling_mean(grp['B'], window=5)
    plt.plot(grp['D'], label='rolling ({k})'.format(k=key))
plt.legend(loc='best')
plt.show()
```


Question:
How to change the tables' fontsize I'm drawing a table with matplotlib.axes.Axes.table like this:
```
sub_axes.table(cellText=table_vals,
          colWidths = [0.15, 0.25],
          rowLabels=row_labels,
          loc='right')
```
I'd like to change the fontsize of table's content, and found there is a fontsize property. So it becomes:
```
sub_axes.table(cellText=table_vals,
          colWidths = [0.15, 0.25],
          rowLabels=row_labels,
          fontsize=12,
          loc='right')
```
But when I execute the code, I got an error:
```
TypeError: table() got an unexpected keyword argument 'fontsize'
```
Is this property deprecated? And how can I change the fontsize of table with pyplot?

Response:
I think the documentation is either hinting at a parameter-to-be (notice fontsize is not a link like the other parameters) or perhaps is a bit misleading at the moment. There is no fontsize parameter. Digging through the source code, I found the Table.set_fontsize method:
```
table = sub_axes.table(cellText=table_vals,
                       colWidths = [0.15, 0.25],
                       rowLabels=row_labels,
                       loc='right')
table.set_fontsize(14)
table.scale(1.5, 1.5)  # may help
```
Here is an example with a grossly exaggerated fontsize just to show the effect.
```
import matplotlib.pyplot as plt
# Based on http://stackoverflow.com/a/8531491/190597 (Andrey Sobolev)

fig = plt.figure()
ax = fig.add_subplot(111)
y = [1, 2, 3, 4, 5, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1]
col_labels = ['col1', 'col2', 'col3']
row_labels = ['row1', 'row2', 'row3']
table_vals = [[11, 12, 13], [21, 22, 23], [31, 32, 33]]

the_table = plt.table(cellText=table_vals,
                      colWidths=[0.1] * 3,
                      rowLabels=row_labels,
                      colLabels=col_labels,
                      loc='center right')
the_table.auto_set_font_size(False)
the_table.set_fontsize(24)
the_table.scale(2, 2)

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


Question: Plot a plane based on a normal vector and a point in Matlab or matplotlib How would one go plotting a plane in matlab or matplotlib from a normal vector and a point?

Response:
For all the copy/pasters out there, here is similar code for Python using matplotlib:
```py
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

point  = np.array([1, 2, 3])
normal = np.array([1, 1, 2])

# a plane is a*x+b*y+c*z+d=0
# [a,b,c] is the normal. Thus, we have to calculate
# d and we're set
d = -point.dot(normal)

# create x,y
xx, yy = np.meshgrid(range(10), range(10))

# calculate corresponding z
z = (-normal[0] * xx - normal[1] * yy - d) * 1. /normal[2]

# plot the surface
plt3d = plt.figure().gca(projection='3d')
plt3d.plot_surface(xx, yy, z)
plt.show()
```
EDIT For newer matplotlib>3.6:
```py
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

point  = np.array([1, 2, 3])
normal = np.array([1, 1, 2])

# a plane is a*x+b*y+c*z+d=0
# [a,b,c] is the normal. Thus, we have to calculate
# d and we're set
d = -point.dot(normal)

# create x,y
xx, yy = np.meshgrid(range(10), range(10))

# calculate corresponding z
z = (-normal[0] * xx - normal[1] * yy - d) * 1. /normal[2]

# plot the surface
fig = plt.figure()
plt3d = fig.add_subplot(projection='3d')
plt3d.plot_surface(xx, yy, z)
plt.show()
```


Question:
How to add a variable to Python plt.title? [duplicate] This question already has answers here: How do I put a variable’s value inside a string (interpolate it into the string)? (9 answers) Closed 5 months ago. I am trying to plot lots of diagrams, and for each diagram, I want to use a variable to label them. How can I add a variable to plt.title? For example:
```
import numpy as np
import matplotlib.pyplot as plt

plt.figure(1)
plt.ylabel('y')
plt.xlabel('x')

for t in xrange(50, 61):
    plt.title('f model: T=t')

    for i in xrange(4, 10):
        plt.plot(1.0 / i, i ** 2, 'ro')

    plt.legend
    plt.show()
```
In the argument of plt.title(), I want t to be variable changing with the loop.

Response:
You can change a value in a string by using %. Documentation can be found here. For example:
```
num = 2
print "1 + 1 = %i" % num # i represents an integer
```
This will output: 1 + 1 = 2 You can also do this with floats and you can choose how many decimal place it will print:
```
num = 2.000
print "1.000 + 1.000 = %1.3f" % num # f represents a float
```
gives: 1.000 + 1.000 = 2.000 Using this in your example to update t in the figure title:
```
plt.figure(1)
plt.ylabel('y')
plt.xlabel('x')

for t in xrange(50,61):
    plt.title('f model: T=%i' %t)

    for i in xrange(4,10):
        plt.plot(1.0/i,i**2,'ro')

    plt.legend
    plt.show()
```


Question: ggplot styles in Python When I look at the plotting style in the Pandas documentation, the plots look different from the default one. It seems to mimic the ggplot "look and feel". Same thing with the seaborn's package. How can I load that style? (even if I am not using a notebook?)

Response:
Update: If you have matplotlib >= 1.4, there is a new style module which has a ggplot style by default. To activate this, use:
```
from matplotlib import pyplot as plt
plt.style.use('ggplot')
```
To see all the available styles, you can check plt.style.available. Similarly, for seaborn styling you can do:
```
plt.style.use('seaborn-white')
```
or, you can use seaborn's own machinery to set up the styling:
```
import seaborn as sns
sns.set()
```
The set() function has more options to select a specific style (see docs). Note that seaborn previously did the above automatically on import, but with the latest versions (>= 0.8) this is no longer the case. If you actually want a ggplot-like syntax in Python as well (and not only the styling), take a look at the plotnine package, which is a grammar of graphics implementation in Python with a syntax very similar to R's ggplot2. Note: the old answer mentioned to do pd.options.display.mpl_style = 'default' . This was however deprecated in pandas in favor of matplotlib's styling using plt.style(..), and in the meantime this functionality is even removed from pandas.


Question:
Changing the formatting of a datetime axis I have a series whose index is datetime that I wish to plot. I want to plot the values of the series on the y axis and the index of the series on the x axis. The Series looks as follows:
```
2014-01-01     7
2014-02-01     8
2014-03-01     9
2014-04-01     8
...
```
I generate a graph using plt.plot(series.index, series.values). But the graph looks like: The problem is that I would like to have only year and month (yyyy-mm or 2016 March). However, the graph contains hours, minutes and seconds. How can I remove them so that I get my desired formatting?

Response:
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# sample data
N = 30
drange = pd.date_range("2014-01", periods=N, freq="MS")
np.random.seed(365)  # for a reproducible example of values
values = {'values':np.random.randint(1,20,size=N)}
df = pd.DataFrame(values, index=drange)

fig, ax = plt.subplots()
ax.plot(df.index, df.values)
ax.set_xticks(df.index)

# use formatters to specify major and minor ticks
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m"))
ax.xaxis.set_minor_formatter(mdates.DateFormatter("%Y-%m"))
_ = plt.xticks(rotation=90)
```


Question:
Fixing x axis scale and autoscale y axis I would like to plot only part of the array, fixing the x part, but letting the y part autoscale. I tried as shown below, but it does not work. Any suggestions?
```
import numpy as np
import matplotlib.pyplot as plt

data=[np.arange(0,101,1),300-0.1*np.arange(0,101,1)]

plt.figure()

plt.scatter(data[0], data[1])
plt.xlim([50,100])
plt.autoscale(enable=True, axis='y')

plt.show()
```

Response:
While Joe Kington certainly proposes the most sensible answer when he recommends that only the necessary data be plotted, there are situations where it would be best to plot all of the data and just zoom to a certain section. Additionally, it would be nice to have an "autoscale_y" function that only requires the axes object (i.e., unlike the answer here, which requires direct use of the data.) Here is a function that just rescales the y-axis based on the data that is in the visible x-region:
```
def autoscale_y(ax,margin=0.1):
    """This function rescales the y-axis based on the data that is visible given the current xlim of the axis.
    ax -- a matplotlib axes object
    margin -- the fraction of the total height of the y-data to pad the upper and lower ylims"""

    import numpy as np

    def get_bottom_top(line):
        xd = line.get_xdata()
        yd = line.get_ydata()
        lo,hi = ax.get_xlim()
        y_displayed = yd[((xd>lo) & (xd<hi))]
        h = np.max(y_displayed) - np.min(y_displayed)
        bot = np.min(y_displayed)-margin*h
        top = np.max(y_displayed)+margin*h
        return bot,top

    lines = ax.get_lines()
    bot,top = np.inf, -np.inf

    for line in lines:
        new_bot, new_top = get_bottom_top(line)
        if new_bot < bot: bot = new_bot
        if new_top > top: top = new_top

    ax.set_ylim(bot,top)
```
This is something of a hack, and will probably not work in many situations, but for a simple plot, it works well. Here is a simple example using this function:
```
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-100,100,1000)
y = x**2 + np.cos(x)*100

fig,axs = plt.subplots(1,2,figsize=(8,5))

for ax in axs:
    ax.plot(x,y)
    ax.plot(x,y*2)
    ax.plot(x,y*10)
    ax.set_xlim(-10,10)

autoscale_y(axs[1])

axs[0].set_title('Rescaled x-axis')
axs[1].set_title('Rescaled x-axis\nand used "autoscale_y"')

plt.show()
```


Question:
Python matplotlib.pyplot pie charts: How to remove the label on the left side? I plot a piechart using pyplot.
```
import pylab
import pandas as pd
test = pd.Series(['male', 'male', 'male', 'male', 'female'], name="Sex")
test = test.astype("category")
groups = test.groupby([test]).agg(len)
groups.plot(kind='pie', shadow=True)
pylab.show()
```
The result: However, I'm unable to remove the label on the left (marked red in the picture). I already tried
```
plt.axes().set_xlabel('')
```
and
```
plt.axes().set_ylabel('')
```
but that did not work.

Response:
You could just set the ylabel by calling pylab.ylabel:
```
pylab.ylabel('')
```
or
```
pylab.axes().set_ylabel('')
```
In your example, plt.axes().set_ylabel('') will not work because you dont have import matplotlib.pyplot as plt in your code, so plt doesn't exist. Alternatively, the groups.plot command returns the Axes instance, so you could use that to set the ylabel:
```
ax=groups.plot(kind='pie', shadow=True)
ax.set_ylabel('')
```


Question:
How to plot a dashed line on seaborn lineplot? I'm simply trying to plot a dashed line using seaborn. This is the code I'm using and the output I'm getting
```
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt

n = 11
x = np.linspace(0,2,n)
y = np.sin(2*np.pi*x)

sns.lineplot(x,y, linestyle='--')
plt.show()
```
What am I doing wrong? Thanks

Response:
It seems that linestyle= argument doesn't work with lineplot(), and the argument dashes= is a bit more complicated than it might seem. A (relatively) simple way of doing it might be to get a list of the Line2D objects on the plot using ax.lines and then set the linestyle manually:
```
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt

n = 11
x = np.linspace(0,2,n)
y = np.sin(2*np.pi*x)

ax = sns.lineplot(x,y)

# Might need to loop through the list if there are multiple lines on the plot
ax.lines[0].set_linestyle("--")

plt.show()
```
Update: It appears the dashes argument applies only when plotting multiple lines (usually using a pandas dataframe). Dashes are specified the same as in matplotlib, a tuple of (segment, gap) lengths. Therefore, you need to pass a list of tuples.
```
n = 100
x = np.linspace(0,4,n)
y1 = np.sin(2*np.pi*x)
y2 = np.cos(2*np.pi*x)

df = pd.DataFrame(np.c_[y1, y2]) # modified @Elliots dataframe production

ax = sns.lineplot(data=df, dashes=[(2, 2), (2, 2)])
plt.show()
```


Question: Changing the color of matplotlib's violin plots Is there a way to change the color of the violin plots in matplotlib? The default color is this "brownish" color, which is not too bad, but I'd like to color e.g., the first 3 violins differently to highlight them. I don't find any parameter in the documentation. Any ideas or hacks to color the violins differently?

Response:
matplotlib.pyplot.violinplot() says it returns: A dictionary mapping each component of the violinplot to a list of the corresponding collection instances created. The dictionary has the following keys: bodies: A list of the matplotlib.collections.PolyCollection instances containing the filled area of each violin. [...among others...] Methods of PolyCollections include: set_color(c) which sets both the facecolor and edgecolor, set_facecolor(c) and set_edgecolor(c) all of which take a "matplotlib color arg or sequence of rgba tuples" So, it looks like you could just loop through the result's body list and modify the facecolor of each:
```
violin_parts = plt.violinplot(...)

for pc in violin_parts['bodies']:
    pc.set_facecolor('red')
    pc.set_edgecolor('black')
```
It is a bit strange though that you can't set this when creating it like the common plot types. I'd guess it's probably because the operation creates so many bits (the aforementioned PolyCollection along with 5 other LineCollections), that additional arguments would be ambiguous.


Question:
How to use `GridSpec()` with `subplots()` There are several (example) SO posts dealing with how to use GridSpec with subplotting in general. What i am trying to achieve to no avail, is to allow the use of GridSpec with subplots, something like this, Where i can replace the actual Array and list indexes with some loop controlled index :
```
gs = gridspec.GridSpec(4, 1, height_ratios=[2, 2, 1, 1])
tPlot, axes = plt.subplots(4, sharex=True, sharey=False)
tPlot.suptitle(node, fontsize=20)
axes[0].plot(targetDay[0], gs[0])
axes[1].plot(targetDay[1], gs[1])
axes[2].scatter(targetDay[2], gs[2])
axes[3].plot(targetDay[3], gs[3])
```
Needless to say that this code does not work, it just an example.

Response:
Rather than calling gridspec.GridSpec before subplots, you can send the kwargs to GridSpec from within your subplots call, using the gridspec_kw argument. From the docs: gridspec_kw : dict Dict with keywords passed to the GridSpec constructor used to create the grid the subplots are placed on. So, for example:
```
import matplotlib.pyplot as plt

tPlot, axes = plt.subplots(
        nrows=4, ncols=1, sharex=True, sharey=False,
        gridspec_kw={'height_ratios':[2,2,1,1]}
        )

tPlot.suptitle('node', fontsize=20)

axes[0].plot(range(10),'ro-')
axes[1].plot(range(10),'bo-')
axes[2].plot(range(10),'go-')
axes[3].plot(range(10),'mo-')

plt.show()
```


Question: Line plot with arrows I have a line graph that I want to plot using arrows instead of lines. That is, the line between successive pairs of points should be an arrow going from the first point to the second point. I know of the arrow function, but that only seems to do individual arrows. Before I work out a way to try and use this to do a whole plot, is there a nicer way to do it?

Response:
You can do this with quiver, but it's a little tricky to get the keyword arguments right.
```
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2*np.pi, 10)
y = np.sin(x)

plt.figure()
plt.quiver(x[:-1], y[:-1], x[1:]-x[:-1], y[1:]-y[:-1], scale_units='xy', angles='xy', scale=1)

plt.show()
```


Question: Matplotlib: Horizontal Linelength in Legend Lets say i'm plotting a line with matplotlib and add a legend. Within the legend it says ------ Label. I find the default horizontal length of this line a bit too long when plotting small figure sizes for print. Is there a property to set ------ Label to --- Label?

Response: When you create your legend add the handlelength keyword (doc) which sets the length of the '---' (which is called the handle).


Question: Can matplotlib add metadata to saved figures? I want to be able to ascertain the provenance of the figures I create using matplotlib, i.e. to know which version of my code and data created these figures. (See this essay for more on provenance.) I imagine the most straightforward approach would be to add the revision numbers of the code and data to the metadata of the saved figures, or as comments in a postscript file for example. Is there any easy way to do this in Matplotlib? The savefig function doesn't seem to be capable of this but has someone come up with a workable solution?

Response:
I don't know of a way using matplotlib, but you can add metadata to png's with PIL:
```
f = "test.png"
METADATA = {"version":"1.0", "OP":"ihuston"}

# Create a sample image
import pylab as plt
import numpy as np
X = np.random.random((50,50))
plt.imshow(X)
plt.savefig(f)

# Use PIL to save some image metadata
from PIL import Image
from PIL import PngImagePlugin

im = Image.open(f)
meta = PngImagePlugin.PngInfo()

for x in METADATA:
    meta.add_text(x, METADATA[x])
im.save(f, "png", pnginfo=meta)

im2 = Image.open(f)
print im2.info
```
This gives:
```
{'version': '1.0', 'OP': 'ihuston'}
```


Question:
matplotlib matshow labels I start using matplotlib a month ago, so I'm still learning. I'm trying to do a heatmap with matshow. My code is the following:
```
data = numpy.array(a).reshape(4, 4)
cax = ax.matshow(data, interpolation='nearest', cmap=cm.get_cmap('PuBu'), norm=LogNorm())
cbar = fig.colorbar(cax)

ax.set_xticklabels(alpha)
ax.set_yticklabels(alpha)
```
where alpha is a model from django with 4fields: 'ABC', 'DEF', 'GHI', 'JKL' the thing is that I don't know why, the label 'ABC' doesn't appear, leaving the last cell without label. If someone would have a clue how to modify my script in a way to appear the 'ABC' I would be grateful :)

Response:
What's happening is that the xticks actually extend outside of the displayed figure when using matshow. (I'm not quite sure exactly why this is. I've almost never used matshow, though.) To demonstrate this, look at the output of ax.get_xticks(). In your case, it's array([-1., 0., 1., 2., 3., 4.]). Therefore, when you set the xtick labels, "ABC" is at , and isn't displayed on the figure. The easiest solution is just to prepend a blank label to your list of labels, e.g.
```
ax.set_xticklabels(['']+alpha)
ax.set_yticklabels(['']+alpha)
```
As a full example:
```
import numpy as np
import matplotlib.pyplot as plt

alpha = ['ABC', 'DEF', 'GHI', 'JKL']

data = np.random.random((4,4))

fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(data, interpolation='nearest')
fig.colorbar(cax)

ax.set_xticklabels(['']+alpha)
ax.set_yticklabels(['']+alpha)

plt.show()
```


Question: Why is matplotlib plotting my circles as ovals? Is there a way to get matplotlib to plot a perfect circle? They look more like ovals.

Response:
Just to expand on DSM's correct answer. By default, plots have more pixels along one axis over the other. When you add a circle, it's traditionally added in data units. If your axes have a symmetric range, that means one step along the x axis will involve a different number of pixels than one step along your y axis. So a symmetric circle in data units is asymmetric in your Pixel units (what you actually see). As DSM correctly pointed out, you can force the x and y axes to have equal number of pixels per data unit. This is done using the plt.axis("equal") or ax.axis("equal") methods (where ax is an instance of an Axes). You can also draw an Ellipse such that it is appropriately scaled to look like a circle on your plot. Here's an example of such a case:
```
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse, Circle

fig = plt.figure()
ax1 = fig.add_subplot(211)
# calculate asymmetry of x and y axes:
x0, y0 = ax1.transAxes.transform((0, 0)) # lower left in pixels
x1, y1 = ax1.transAxes.transform((1, 1)) # upper right in pixes
dx = x1 - x0
dy = y1 - y0
maxd = max(dx, dy)
width = .15 * maxd / dx
height = .15 * maxd / dy

# a circle you expect to be a circle, but it is not
ax1.add_artist(Circle((.5, .5), .15))
# an ellipse you expect to be an ellipse, but it's a circle
ax1.add_artist(Ellipse((.75, .75), width, height))
ax2 = fig.add_subplot(212)

ax2.axis('equal')
# a circle you expect to be a circle, and it is
ax2.add_artist(Circle((.5, .5), .15))
# an ellipse you expect to be an ellipse, and it is
ax2.add_artist(Ellipse((.75, .75), width, height))

fig.savefig('perfectCircle1.png')
```
resulting in this figure: Alternatively, you can adjust your figure so that the Axes are square:
```
# calculate dimensions of axes 1 in figure units
x0, y0, dx, dy = ax1.get_position().bounds
maxd = max(dx, dy)
width = 6 * maxd / dx
height = 6 * maxd / dy

fig.set_size_inches((width, height))

fig.savefig('perfectCircle2.png')
```
resulting in: Notice how the second axes, which has the axis("equal") option, now has the same range for the x and y axes. The figure has been scaled so that the date units of each are represented by the same number of pixels. You can also adjust your axes to be square, even if the figure is not. Or you can change the default transform for the Circle to None, which means the units used are pixels. I'm having difficulty successfully doing this at the moment (the circle is a circle, but not where I want it to be).


Question:
Matplotlib chart does not display in PyCharm I run the following code in PyCharm 3.4.1, and it highlighted %matplotlib inline showing syntax error, and I delete the first line, and run, I expect it will prompt me some charts, but it runs normally with Process finished with exit code 0， and no charts is showing. My question is: 1. What is %matplotlib inline use for; 2. How to let pycharm shows matplotlib chart?
```
%matplotlib inline
from IPython.core.pylabtools import figsize
import numpy as np
from matplotlib import pyplot as plt
figsize(11, 9)

import scipy.stats as stats

dist = stats.beta
n_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]
data = stats.bernoulli.rvs(0.5, size=n_trials[-1])
x = np.linspace(0, 1, 100)

# For the already prepared, I'm using Binomial's conj. prior.
for k, N in enumerate(n_trials):
    sx = plt.subplot(len(n_trials) / 2, 2, k + 1)
    plt.xlabel("$p$, probability of heads") \
        if k in [0, len(n_trials) - 1] else None
    plt.setp(sx.get_yticklabels(), visible=False)
    heads = data[:N].sum()
    y = dist.pdf(x, 1 + heads, 1 + N - heads)
    plt.plot(x, y, label="observe %d tosses,\n %d heads" % (N, heads))
    plt.fill_between(x, 0, y, color="#348ABD", alpha=0.4)
    plt.vlines(0.5, 0, 4, color="k", linestyles="--", lw=1)

    leg = plt.legend()
    leg.get_frame().set_alpha(0.4)
    plt.autoscale(tight=True)

plt.suptitle("Bayesian updating of posterior probabilities",
             y=1.02,
             fontsize=14)

plt.tight_layout()
```

Response:
The % notation is for magic functions. The particular magic function and argument you reference, %matplotlib inline, is meant for an IPython notebook session. You will get a syntax error using magic functions in a normal python session. The %matplotlib magic function is meant to specify a backend for matplotlib and the argument inline will produce an error if you are not in an IPython notebook session. To show your plot you should use plt.show for an interactive window or plt.savefig to save it to file. For example,
```
plt.show()
```
or
```
plt.savefig( 'myfig.png' )
```


Question:
Matplotlib savefig does not save axes I'm trying to save a figure that works fine in IPython inline but does not save the figure to disk with the axes and titles included. I am using TKAgg backend by default in matplotlibrc. Any ideas what might be going wrong here? I have clearly set the xlabel and the tick marks work correctly in IPython inline plot.
```
import matplotlib.pylab as plt
x = [1,2,3,3]
y = map(lambda(x): x * 2, x)
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.set_title("bleh")
ax.set_xlabel("xlabel")
ax.plot(x, y, 'r--')
fig.savefig("fig.png")
```

Response:
Defining fig = plt.figure(figsize=(15,10)) at the beginning, saving the file as .jpg, and setting bbox_inches='tight' solved the issue for me.
```py
plt.savefig('filename.jpg',bbox_inches='tight', dpi=150)
```
bbox_inches='tight' seems to fix cropping issues but it didn't work for .png.


Question:
Adding a background image to a plot Say I am plotting a set of points with an image as a background. I've used the Lena image in the example:
```
import numpy as np
import matplotlib.pyplot as plt
from scipy.misc import imread

np.random.seed(0)
x = np.random.uniform(0.0,10.0,15)
y = np.random.uniform(0.0,10.0,15)
img = imread("lena.jpg")
plt.scatter(x,y,zorder=1)
plt.imshow(img,zorder=0)
plt.show()
```
This gives me . My question is: How can I specify the corner coordinates of the image in the plot? Let's say I'd like the bottom-left corner to be at x, y = 0.5, 1.0 and the top-right corner to be at x, y = 8.0, 7.0.

Response:
Use the extent keyword of imshow. The order of the argument is [left, right, bottom, top]
```
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(0)
x = np.random.uniform(0.0,10.0,15)
y = np.random.uniform(0.0,10.0,15)

datafile = 'lena.jpg'
img = plt.imread(datafile)
plt.scatter(x,y,zorder=1)
plt.imshow(img, zorder=0, extent=[0.5, 8.0, 1.0, 7.0])
plt.show()
```
For cases where it's desired to have an image in a small area of the scatter plot, change the order of the plots (.imshow then .scatter) and change the extent values.
```py
plt.imshow(img, zorder=0, extent=[3.0, 5.0, 3.0, 4.50])
plt.scatter(x, y, zorder=1)
plt.show()
```


Question:
Pandas: Adding new column to dataframe which is a copy of the index column I have a dataframe which I want to plot with matplotlib, but the index column is the time and I cannot plot it. This is the dataframe (df3): but when I try the following:
```
plt.plot(df3['magnetic_mag mean'], df3['YYYY-MO-DD HH-MI-SS_SSS'], label='FDI')
```
I'm getting an error obviously:
```
KeyError: 'YYYY-MO-DD HH-MI-SS_SSS'
```
So what I want to do is to add a new extra column to my dataframe (named 'Time) which is just a copy of the index column. How can I do it? This is the entire code:
```
#Importing the csv file into df
df = pd.read_csv('university2.csv', sep=";", skiprows=1)

#Changing datetime
df['YYYY-MO-DD HH-MI-SS_SSS'] = pd.to_datetime(df['YYYY-MO-DD HH-MI-SS_SSS'],
                                               format='%Y-%m-%d %H:%M:%S:%f')

#Set index from column
df = df.set_index('YYYY-MO-DD HH-MI-SS_SSS')

#Add Magnetic Magnitude Column
df['magnetic_mag'] = np.sqrt(df['MAGNETIC FIELD X (μT)']**2 + df['MAGNETIC FIELD Y (μT)']**2 + df['MAGNETIC FIELD Z (μT)']**2)

#Subtract Earth's Average Magnetic Field from 'magnetic_mag'
df['magnetic_mag'] = df['magnetic_mag'] - 30

#Copy interesting values
df2 = df[[ 'ATMOSPHERIC PRESSURE (hPa)',
          'TEMPERATURE (C)', 'magnetic_mag']].copy()

#Hourly Average and Standard Deviation for interesting values
df3 = df2.resample('H').agg(['mean','std'])
df3.columns = [' '.join(col) for col in df3.columns]

df3.reset_index()
plt.plot(df3['magnetic_mag mean'], df3['YYYY-MO-DD HH-MI-SS_SSS'], label='FDI')
```
Thank you !!

Response:
I think you need reset_index:
```
df3 = df3.reset_index()
```
Possible solution, but I think inplace is not good practice, check this and this:
```
df3.reset_index(inplace=True)
```
But if you need new column, use:
```
df3['new'] = df3.index
```
I think you can read_csv better:
```
df = pd.read_csv('university2.csv',
                 sep=";",
                 skiprows=1,
                 index_col='YYYY-MO-DD HH-MI-SS_SSS',
                 parse_dates='YYYY-MO-DD HH-MI-SS_SSS') #if doesnt work, use pd.to_datetime
```
And then omit:
```
#Changing datetime
df['YYYY-MO-DD HH-MI-SS_SSS'] = pd.to_datetime(df['YYYY-MO-DD HH-MI-SS_SSS'],
                                               format='%Y-%m-%d %H:%M:%S:%f')
#Set index from column
df = df.set_index('YYYY-MO-DD HH-MI-SS_SSS')
```
EDIT: If MultiIndex or Index is from groupby operation, possible solutions are:
```
df = pd.DataFrame({'A':list('aaaabbbb'),
                   'B':list('ccddeeff'),
                   'C':range(8),
                   'D':range(4,12)})
print (df)
   A  B  C   D
0  a  c  0   4
1  a  c  1   5
2  a  d  2   6
3  a  d  3   7
4  b  e  4   8
5  b  e  5   9
6  b  f  6  10
7  b  f  7  11

df1 = df.groupby(['A','B']).sum()
print (df1)
      C   D
A B
a c   1   9
  d   5  13
b e   9  17
  f  13  21
```
Add parameter as_index=False:
```
df2 = df.groupby(['A','B'], as_index=False).sum()
print (df2)
   A  B   C   D
0  a  c   1   9
1  a  d   5  13
2  b  e   9  17
3  b  f  13  21
```
Or add reset_index:
```
df2 = df.groupby(['A','B']).sum().reset_index()
print (df2)
   A  B   C   D
0  a  c   1   9
1  a  d   5  13
2  b  e   9  17
3  b  f  13  21
```


Question:
Importing an svg file into a matplotlib figure I like to produce high quality plots and therefore avoid rasterized graphics as much as possible. I am trying to import an svg file on to a matplotlib figure:
```
import matplotlib.pyplot as plt
earth   = plt.imread('./gfx/earth.svg')
fig, ax = plt.subplots()
im      = ax.imshow(earth)
plt.show()
```
This works with png perfectly. Can somebody tell me how to do it with svg or at least point my to proper documentation. I know that a similar question has been asked (but not answered): here. Has anything changed since? P.S. I know that I could just export a high resolution png and achieve a similar effect. This is not the solution I am looking for. Here is the image I would like to import: .

Response:
Maybe what you are looking for is svgutils
```
import svgutils.compose as sc
from IPython.display import SVG # /!\ note the 'SVG' function also in svgutils.compose
import numpy as np

# drawing a random figure on top of your SVG
fig, ax = plt.subplots(1, figsize=(4,4))
ax.plot(np.sin(np.linspace(0,2.*np.pi)), np.cos(np.linspace(0,2.*np.pi)), 'k--', lw=2.)
ax.plot(np.random.randn(20)*.3, np.random.randn(20)*.3, 'ro', label='random sampling')
ax.legend()
ax2 = plt.axes([.2, .2, .2, .2])
ax2.bar([0,1], [70,30])
plt.xticks([0.5,1.5], ['water  ', ' ground'])
plt.yticks([0,50])
plt.title('ratio (%)')
fig.savefig('cover.svg', transparent=True)
# here starts the assembling using svgutils
sc.Figure("8cm", "8cm",
    sc.Panel(sc.SVG("./Worldmap_northern.svg").scale(0.405).move(36,29)),
    sc.Panel(sc.SVG("cover.svg"))
    ).save("compose.svg")
SVG('compose.svg')
```
Output:


Question:
Is it possible to do additive blending with matplotlib? When dealing with overlapping high density scatter or line plots of different colors it can be convenient to implement additive blending schemes, where the RGB colors of each marker add together to produce the final color in the canvas. This is a common operation in 2D and 3D render engines. However, in Matplotlib I've only found support for alpha/opacity blending. Is there any roundabout way of doing it or am I stuck with rendering to bitmap and then blending them in some paint program? Edit: Here's some example code and a manual solution. This will produce two partially overlapping random distributions:
```
x1 = randn(1000)
y1 = randn(1000)
x2 = randn(1000) * 5
y2 = randn(1000)
scatter(x1,y1,c='b',edgecolors='none')
scatter(x2,y2,c='r',edgecolors='none')
```
This will produce in matplotlib the following: As you can see, there are some overlapping blue points that are occluded by red points and we would like to see them. By using alpha/opacity blending in matplotlib, you can do:
```
scatter(x1,y1,c='b',edgecolors='none',alpha=0.5)
scatter(x2,y2,c='r',edgecolors='none',alpha=0.5)
```
Which will produce the following: But what I really want is the following: I can do it manually by rendering each plot independently to a bitmap:
```
xlim = plt.xlim()
ylim = plt.ylim()
scatter(x1,y1,c='b',edgecolors='none')
plt.xlim(xlim)
plt.ylim(ylim)
scatter(x2,y2,c='r',edgecolors='none')
plt.xlim(xlim)
plt.ylim(ylim)
plt.savefig(r'scatter_blue.png',transparent=True)
plt.savefig(r'scatter_red.png',transparent=True)
```
Which gives me the following images: What you can do then is load them as independent layers in Paint.NET/PhotoShop/gimp and just additive blend them. Now ideal would be to be able to do this programmatically in Matplotlib, since I'll be processing hundreds of these!

Response:
If you only need an image as the result, you can get the canvas buffer as a numpy array, and then do the blending, here is an example:
```
from matplotlib import pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.scatter(x1,y1,c='b',edgecolors='none')
ax.set_xlim(-4, 4)
ax.set_ylim(-4, 4)
ax.patch.set_facecolor("none")
ax.patch.set_edgecolor("none")
fig.canvas.draw()

w, h = fig.canvas.get_width_height()
img = np.frombuffer(fig.canvas.buffer_rgba(), np.uint8).reshape(h, w, -1).copy()

ax.clear()
ax.scatter(x2,y2,c='r',edgecolors='none')
ax.set_xlim(-4, 4)
ax.set_ylim(-4, 4)
ax.patch.set_facecolor("none")
ax.patch.set_edgecolor("none")
fig.canvas.draw()

img2 = np.frombuffer(fig.canvas.buffer_rgba(), np.uint8).reshape(h, w, -1).copy()

img[img[:, :, -1] == 0] = 0
img2[img2[:, :, -1] == 0] = 0

fig.clf()

plt.imshow(np.maximum(img, img2))
plt.subplots_adjust(0, 0, 1, 1)
plt.axis("off")
plt.show()
```
the result:


Question:
Barplot savefig() returning an AttributeError I'm converting an iPython notebook to a python script, just trying to output the results of a couple Seaborn plots as png files. Code:
```
import seaborn as sns

...

sns.set_style("whitegrid")
ax = sns.barplot(x=range(1,11), y=[ (x/nrows)*100 for x in addr_pop ], palette="Blues_d")
ax.savefig("html/addr_depth.png")
```
Don't worry about the variables, they're populated as expected, and I get a great-looking chart in iPyNB. Running the code within a script, however, yields RuntimeError: Invalid DISPLAY variable. Following another thread, I modified the code, putting this at the top of the script:
```
import matplotlib
matplotlib.use('Agg')
```
And tried again. This time, it doesn't seem like the savefig() method is available for the plot at all:
```
AttributeError: 'AxesSubplot' object has no attribute 'savefig'
```
All the results searching out this error are related to pandas and a plot that is already being displayed. I'm just trying to get Seaborn to output the fig to a file, ideally without displaying it at all. Any help is appreciated.

Response:
I solved the issue by changing
```
ax.savefig('file.png')
```
to
```
ax.figure.savefig('file.png')
```
I guess accessing the figure directly is one way to get to the savefig() method for the barplot. @WoodChopper also has a working solution, but it requires another import statement, and utilizing pyplot's savefig() directly. Either solution does require setting matplotlib.use('Agg') to get around the DISPLAY variable error. As the referenced post noted, this has to be set before importing other matplotlib libraries.


Question:
How can I draw scatter trend line? I want to draw a scatter trend line on matplot. How can I do that? Python
```
import pandas as pd
import matplotlib.pyplot as plt
csv = pd.read_csv('/tmp/test.csv')
data = csv[['fee', 'time']]
x = data['fee']
y = data['time']
plt.scatter(x, y)
plt.show()
```
CSV
```
fee,time
100,650
90,700
80,860
70,800
60,1000
50,1200
```
time is integer value. Scatter chart

Response:
I'm sorry I found the answer by myself. How to add trendline in python matplotlib dot (scatter) graphs? Python
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
csv = pd.read_csv('/tmp/test.csv')
data = csv[['fee', 'time']]
x = data['fee']
y = data['time']
plt.scatter(x, y)

z = np.polyfit(x, y, 1)
p = np.poly1d(z)
plt.plot(x,p(x),"r--")

plt.show()
```
Chart


Question:
How to disable the minor ticks of log-plot in Matplotlib? Here is a simple plot: 1) How to disable the ticks? 2) How to reduce their number? Here is a sample code:
```
from pylab import *
import numpy as np

x = [5e-05, 5e-06, 5e-07, 5e-08, 5e-09, 5e-10]
y = [-13, 14, 100, 120, 105, 93]

def myfunc(x,p):
    sl,yt,yb,ec=p
    y = yb + (yt-yb)/(1+np.power(10, sl*(np.log10(x)-np.log10(ec))))
    return y

xp = np.power(10, np.linspace(np.log10(min(x)/10), np.log10(max(x)*10), 100))

pxp=myfunc(xp, [1,100,0,1e-6])
subplot(111,axisbg="#dfdfdf")
plt.plot(x, y, '.', xp, pxp, 'g-', linewidth=1)
plt.xscale('log')

plt.grid(True,ls="-", linewidth=0.4, color="#ffffff", alpha=0.5)

plt.draw()
plt.show()
```
Which produces:

Response:
```
plt.minorticks_off()
```
Turns em off! To change the number of them/position them, you can use the subsx parameter. like this:
```
plt.xscale('log', subsx=[2, 3, 4, 5, 6, 7, 8, 9])
```
From the docs: subsx/subsy: Where to place the subticks between each major tick. Should be a sequence of integers. For example, in a log10 scale: [2, 3, 4, 5, 6, 7, 8, 9] will place 8 logarithmically spaced minor ticks between each major tick.


Question:
Matplotlib graphic image to base64 Problem : Need to transform a graphic image of matplotlib to a base64 image Current Solution : Save the matplot image in a cache folder and read it with read() method and then convert to base64 New Problem : Annoyance : Need a workaround so I dont need to save the graphic as image in any folder. I want to just use the image in the memory. Doing unnecessary I/O is a bad practice.
```
def save_single_graphic_data(data, y_label="Loss", x_label="Epochs", save_as="data.png"):
    total_epochs = len(data)
    plt.figure()
    plt.clf()

    plt.plot(total_epochs, data)

    ax = plt.gca()
    ax.ticklabel_format(useOffset=False)

    plt.ylabel(y_label)
    plt.xlabel(x_label)

    if save_as is not None:
        plt.savefig(save_as)

    plt.savefig("cache/cached1.png")

    cached_img = open("cache/cached1.png")

    cached_img_b64 = base64.b64encode(cached_img.read())

    os.remove("cache/cached1.png")

    return cached_img_b64
```

Response:
```
import cStringIO
my_stringIObytes = cStringIO.StringIO()
plt.savefig(my_stringIObytes, format='jpg')
my_stringIObytes.seek(0)
my_base64_jpgData = base64.b64encode(my_stringIObytes.read())
```
[edit] in python3 it should be
```
import io
my_stringIObytes = io.BytesIO()
plt.savefig(my_stringIObytes, format='jpg')
my_stringIObytes.seek(0)
my_base64_jpgData = base64.b64encode(my_stringIObytes.read()).decode()
```
I think at least ... based on the documentation http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.savefig


Question:
Plot pie chart and table of pandas dataframe I have to plot pie-chart and a table side by side using matplotlib. For drawing the pie-chart, I use the below code:
```
import matplotlib.pyplot as plt
df1.EventLogs.value_counts(sort=False).plot.pie()
plt.show()
```
For drawing a table, I use the below code:
```
%%chart table --fields MachineName --data df_result2
```
df_result2 is a table with the list of MachineName's in it. Not sure whether we can place both pie chart and table side by side. Any help would be appreciated.

Response:
Look at the code:
```
import pandas as pd
import matplotlib.pyplot as plt
from pandas.tools.plotting import table

# sample data
raw_data = {'officer_name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
        'jan_arrests': [4, 24, 31, 2, 3],
        'feb_arrests': [25, 94, 57, 62, 70],
        'march_arrests': [5, 43, 23, 23, 51]}
df = pd.DataFrame(raw_data, columns = ['officer_name', 'jan_arrests', 'feb_arrests', 'march_arrests'])
df['total_arrests'] = df['jan_arrests'] + df['feb_arrests'] + df['march_arrests']

plt.figure(figsize=(16,8))
# plot chart
ax1 = plt.subplot(121, aspect='equal')
df.plot(kind='pie', y = 'total_arrests', ax=ax1, autopct='%1.1f%%',
 startangle=90, shadow=False, labels=df['officer_name'], legend = False, fontsize=14)

# plot table
ax2 = plt.subplot(122)
plt.axis('off')
tbl = table(ax2, df, loc='center')
tbl.auto_set_font_size(False)
tbl.set_fontsize(14)
plt.show()
```


Question: Saving an imshow-like image while preserving resolution I have an (n, m) array that I've been visualizing with matplotlib.pyplot.imshow. I'd like to save this data in some type of raster graphics file (e.g. a png) so that: The colors are the ones shown with imshow Each element of the underlying array is exactly one pixel in the saved image -- meaning that if the underlying array is (n, m) elements, the image is NxM pixels. (I'm not interested in interpolation='nearest' in imshow.) There is nothing in the saved image except for the pixels corresponding to the data in the array. (I.e. there's no white space around the edges, axes, etc.) How can I do this? I've seen some code that can kind of do this by using interpolation='nearest' and forcing matplotlib to (grudgingly) turn off axes, whitespace, etc. However, there must be some way to do this more directly -- maybe with PIL? After all, I have the underlying data. If I can get an RGB value for each element of the underlying array, then I can save it with PIL. Is there some way to extract the RGB data from imshow? I can write my own code to map the array values to RGB values, but I don't want to reinvent the wheel, since that functionality already exists in matplotlib.

Response:
As you already guessed there is no need to create a figure. You basically need three steps. Normalize your data, apply the colormap, save the image. matplotlib provides all the necessary functionality:
```
import numpy as np
import matplotlib.pyplot as plt

# some data (512x512)
import scipy.misc
data = scipy.misc.lena()

# a colormap and a normalization instance
cmap = plt.cm.jet
norm = plt.Normalize(vmin=data.min(), vmax=data.max())

# map the normalized data to colors
# image is now RGBA (512x512x4)
image = cmap(norm(data))

# save the image
plt.imsave('test.png', image)
```
While the code above explains the single steps, you can also let imsave do all three steps (similar to imshow):
```
plt.imsave('test.png', data, cmap=cmap)
```
Result (test.png):


Question:
set_data and autoscale_view matplotlib I have multiple lines to be drawn on the same axes, and each of them are dynamically updated (I use set_data), The issue being that i am not aware of the x and y limits of each of the lines. And axes.autoscale_view(True,True,True) / axes.set_autoscale_on(True) are not doing what they are supposed to. How do i auto scale my axes?
```
import matplotlib.pyplot as plt

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

axes.set_autoscale_on(True)
axes.autoscale_view(True,True,True)

l1, = axes.plot([0,0.1,0.2],[1,1.1,1.2])
l2, = axes.plot([0,0.1,0.2],[-0.1,0,0.1])

#plt.show() #shows the auto scaled.

l2.set_data([0,0.1,0.2],[-1,-0.9,-0.8])

#axes.set_ylim([-2,2]) #this works, but i cannot afford to do this.

plt.draw()
plt.show() #does not show auto scaled
```
I have referred to these already, this , this. In all cases I have come across, the x,y limits are known. I have multiple lines on the axes and their ranges change, keeping track of the ymax for the entire data is not practical A little bit of exploring got me to this,
```
xmin,xmax,ymin,ymax = matplotlib.figure.FigureImage.get_extent(FigureImage)
```
But here again, i do not know how to access FigureImage from the Figure instance. Using matplotlib 0.99.3

Response:
From the matplotlib docs for autoscale_view: The data limits are not updated automatically when artist data are changed after the artist has been added to an Axes instance. In that case, use matplotlib.axes.Axes.relim() prior to calling autoscale_view. So, you'll need to add two lines before your plt.draw() call after the set_data call:
```
axes.relim()
axes.autoscale_view(True,True,True)
```