Question:
How to change the font size on a matplotlib plot How does one change the font size for all elements (ticks, labels, title) on a matplotlib plot? I know how to change the tick label sizes, this is done with:
```
import matplotlib
matplotlib.rc('xtick', labelsize=20)
matplotlib.rc('ytick', labelsize=20)
```
But how does one change the rest?

Response:
From the matplotlib documentation,
```
font = {'family' : 'normal',
        'weight' : 'bold',
        'size'   : 22}

matplotlib.rc('font', **font)
```
This sets the font of all items to the font specified by the kwargs object, font. Alternatively, you could also use the rcParams update method as suggested in this answer:
```
matplotlib.rcParams.update({'font.size': 22})
```
or
```
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 22})
```
You can find a full list of available properties on the Customizing matplotlib page.


Question:
How to plot two columns of a pandas data frame using points I have a pandas dataframe and would like to plot values from one column versus the values from another column. Fortunately, there is plot method associated with the dataframes that seems to do what I need:
```py
df.plot(x='col_name_1', y='col_name_2')
```
Unfortunately, it looks like among the plot styles (listed here after the kind parameter), there are not points. I can use lines or bars or even density but not points. Is there a work around that can help to solve this problem?

Response:
You can specify the style of the plotted line when calling df.plot:
```
df.plot(x='col_name_1', y='col_name_2', style='o')
```
The style argument can also be a dict or list, e.g.:
```
import numpy as np
import pandas as pd

d = {'one' : np.random.rand(10),
     'two' : np.random.rand(10)}

df = pd.DataFrame(d)

df.plot(style=['o','rx'])
```
All the accepted style formats are listed in the documentation of matplotlib.pyplot.plot.


Question:
How to Display Dataframe next to Plot in Jupyter Notebook I understand how to display two plots next to each other (horizontally) in Jupyter Notebook, but I don't know if there is a way to display a plot with a dataframe next to it. I imagine it could look something like this: However, I'm not able to do this, and whenever I print out the dataframe, it appears below my plot... Here is a similar question, but I am also outputting plots within this same cell that I want to be vertically oriented. I currently have this:
```
# line plots
df_plot[['DGO %chg','DLM %chg']].plot(figsize=(15,5),grid=True)
plt.ylim((-ylim,ylim))

df_plot[['Diff']].plot(kind='area',color='lightgrey',figsize=(15,1))
plt.xticks([])
plt.xlabel('')
plt.ylim((0,ylim_diff))
plt.show()

# scatter plots
plt.scatter(x=df_scat[:-7]['DGO'],y=df_scat[:-7]['DLM'])
plt.scatter(x=df_scat[-7:]['DGO'],y=df_scat[-7:]['DLM'],color='red')
plt.title('%s Cluster Last 7 Days'%asset)
plt.show()

# display dataframe
# display(df_scat[['DGO','DLM']][:10]) <-- prints underneath, not working
```
Where the red box shows where I want my dataframe to appear. Does anyone have any ideas about how to do this? Thanks for your thoughts!

Response:
I'm not aware of how to control the location of where the DataFrame will display directly - but one work around I have used in the past is to render the DataFrame as a matplotlib table and then it should behave like any other matplotlib plot. You can use:
```
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

df = pd.DataFrame()
df['x'] = np.arange(0,11)
df['y'] = df['x']*2

fig = plt.figure(figsize=(8,5))

ax1 = fig.add_subplot(121)
ax1.scatter(x=df['x'],y=df['y'])

ax2 = fig.add_subplot(122)
font_size=14
bbox=[0, 0, 1, 1]
ax2.axis('off')
mpl_table = ax2.table(cellText = df.values, rowLabels = df.index, bbox=bbox, colLabels=df.columns)
mpl_table.auto_set_font_size(False)
mpl_table.set_fontsize(font_size)
```


Question:
Horizontal stacked bar plot and add labels to each section I am trying to replicate the following image in matplotlib and it seems barh is my only option. Though it appears that you can't stack barh graphs so I don't know what to do If you know of a better python library to draw this kind of thing, please let me know. This is all I could come up with as a start:
```
import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt

people = ('A','B','C','D','E','F','G','H')
y_pos = np.arange(len(people))
bottomdata = 3 + 10 * np.random.rand(len(people))
topdata = 3 + 10 * np.random.rand(len(people))
fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(111)
ax.barh(y_pos, bottomdata,color='r',align='center')
ax.barh(y_pos, topdata,color='g',align='center')
ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.set_xlabel('Distance')

plt.show()
```
I would then have to add labels individually using ax.text which would be tedious. Ideally I would like to just specify the width of the part to be inserted then it updates the center of that section with a string of my choosing. The labels on the outside (e.g. 3800) I can add myself later, it is mainly the labeling over the bar section itself and creating this stacked method in a nice way I'm having problems with. Can you even specify a 'distance' i.e. span of color in any way?

Response:
Edit 2: for more heterogeneous data. (I've left the above method since I find it more usual to work with the same number of records per series) Answering the two parts of the question: a) barh returns a container of handles to all the patches that it drew. You can use the coordinates of the patches to aid the text positions. b) Following these two answers to the question that I noted before (see Horizontal stacked bar chart in Matplotlib), you can stack bar graphs horizontally by setting the 'left' input. and additionally c) handling data that is less uniform in shape. Below is one way you could handle data that is less uniform in shape is simply to process each segment independently.
```
import numpy as np
import matplotlib.pyplot as plt

# some labels for each row
people = ('A','B','C','D','E','F','G','H')
r = len(people)

# how many data points overall (average of 3 per person)
n = r * 3

# which person does each segment belong to?
rows = np.random.randint(0, r, (n,))
# how wide is the segment?
widths = np.random.randint(3,12, n,)
# what label to put on the segment (xrange in py2.7, range for py3)
labels = range(n)
colors ='rgbwmc'

patch_handles = []

fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(111)

left = np.zeros(r,)
row_counts = np.zeros(r,)

for (r, w, l) in zip(rows, widths, labels):
    print r, w, l
    patch_handles.append(ax.barh(r, w, align='center', left=left[r],
        color=colors[int(row_counts[r]) % len(colors)]))
    left[r] += w
    row_counts[r] += 1
    # we know there is only one patch but could enumerate if expanded
    patch = patch_handles[-1][0]
    bl = patch.get_xy()
    x = 0.5*patch.get_width() + bl[0]
    y = 0.5*patch.get_height() + bl[1]
    ax.text(x, y, "%d%%" % (l), ha='center',va='center')

y_pos = np.arange(8)
ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.set_xlabel('Distance')

plt.show()
```
Which produces a graph like this , with a different number of segments present in each series. Note that this is not particularly efficient since each segment used an individual call to ax.barh. There may be more efficient methods (e.g. by padding a matrix with zero-width segments or nan values) but this likely to be problem-specific and is a distinct question. Edit: updated to answer both parts of the question.
```
import numpy as np
import matplotlib.pyplot as plt

people = ('A','B','C','D','E','F','G','H')
segments = 4

# generate some multi-dimensional data & arbitrary labels
data = 3 + 10* np.random.rand(segments, len(people))
percentages = (np.random.randint(5,20, (len(people), segments)))
y_pos = np.arange(len(people))

fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(111)

colors ='rgbwmc'
patch_handles = []
left = np.zeros(len(people)) # left alignment of data starts at zero
for i, d in enumerate(data):
    patch_handles.append(ax.barh(y_pos, d,
      color=colors[i%len(colors)], align='center',
      left=left))
    # accumulate the left-hand offsets
    left += d

# go through all of the bar segments and annotate
for j in range(len(patch_handles)):
    for i, patch in enumerate(patch_handles[j].get_children()):
        bl = patch.get_xy()
        x = 0.5*patch.get_width() + bl[0]
        y = 0.5*patch.get_height() + bl[1]
        ax.text(x,y, "%d%%" % (percentages[i,j]), ha='center')

ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.set_xlabel('Distance')

plt.show()
```
You can achieve a result along these lines (note: the percentages I used have nothing to do with the bar widths, as the relationship in the example seems unclear): See Horizontal stacked bar chart in Matplotlib for some ideas on stacking horizontal bar plots.


Question:
Adjust size of ConfusionMatrixDisplay (ScikitLearn) How to set the size of the figure ploted by ScikitLearn's Confusion Matrix?
```py
import numpy as np
from sklearn.metrics import ConfusionMatrixDisplay, confusion_matrix
cm = confusion_matrix(np.arange(25), np.arange(25))
cmp = ConfusionMatrixDisplay(cm, display_labels=np.arange(25))
cmp.plot()
```
The code above shows this figure, which is too tight:

Response:
You can send a matplotlib.axes object to the .plot method of sklearn.metrics.ConfusionMatrixDisplay. Set the size of the figure in matplotlib.pyplot.subplots first.
```py
import numpy as np
from sklearn.metrics import ConfusionMatrixDisplay, confusion_matrix
import matplotlib.pyplot as plt

cm = confusion_matrix(np.arange(25), np.arange(25))
cmp = ConfusionMatrixDisplay(cm, display_labels=np.arange(25))
fig, ax = plt.subplots(figsize=(10,10))
cmp.plot(ax=ax)
```


Question:
surface plots in matplotlib I have a list of 3-tuples representing a set of points in 3D space. I want to plot a surface that covers all these points. The plot_surface function in the mplot3d package requires as arguments X,Y and Z to be 2d arrays. Is plot_surface the right function to plot surface and how do I transform my data into the required format?
```
data = [(x1,y1,z1),(x2,y2,z2),.....,(xn,yn,zn)]
```

Response:
For surfaces it's a bit different than a list of 3-tuples, you should pass in a grid for the domain in 2d arrays. If all you have is a list of 3d points, rather than some function f(x, y) -> z, then you will have a problem because there are multiple ways to triangulate that 3d point cloud into a surface. Here's a smooth surface example:
```
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
# Axes3D import has side effects, it enables using projection='3d' in add_subplot
import matplotlib.pyplot as plt
import random

def fun(x, y):
    return x**2 + y

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = y = np.arange(-3.0, 3.0, 0.05)
X, Y = np.meshgrid(x, y)
zs = np.array(fun(np.ravel(X), np.ravel(Y)))
Z = zs.reshape(X.shape)

ax.plot_surface(X, Y, Z)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()
```


Question:
Set y axis limit in Pandas histogram I am using Pandas histogram. I would like to set the y-axis range of the plot. Here is the context:
```
import matplotlib.pyplot as plt
%matplotlib inline

interesting_columns = ['Level', 'Group']

for column in interesting_columns:
    data['ranking'].hist(by=data[column], normed=True)
```
There is a range argument that can filter x-values, but I am unaware of the y equivalent:
```
hist(by=[column], normed=True, range=[0, 1]) #working argument
hist(by=[column], normed=True, y_range=[0, 1]) #hypothetical argument
```
I've read a lot of different methods for changing plot ranges using plt attributes. They do not seem to work in a loop and for subplots. I am struggling to grasp the right way to approach this problem.

Response:
If you use
```
data['ranking'].plot.hist(ylim=(0,1))
```
(mind the .plot in the syntax!) it should work.


Question:
Matplotlib plot with variable line width Is it possible to plot a line with variable line width in matplotlib? For example:
```
from pylab import *
x = [1, 2, 3, 4, 5]
y = [1, 2, 2, 0, 0]
width = [.5, 1, 1.5, .75, .75]

plot(x, y, linewidth=width)
```
This doesn't work because linewidth expects a scalar. Note: I'm aware of *fill_between()* and *fill_betweenx()*. Because these only fill in x or y direction, these do not do justice to cases where you have a slanted line. It is desirable for the fill to always be normal to the line. That is why a variable width line is sought.

Response:
Use LineCollections. A way to do it along the lines of this Matplotlib example is
```
import numpy as np
from matplotlib.collections import LineCollection
import matplotlib.pyplot as plt
x = np.linspace(0,4*np.pi,10000)
y = np.cos(x)
lwidths=1+x[:-1]
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
lc = LineCollection(segments, linewidths=lwidths,color='blue')
fig,a = plt.subplots()
a.add_collection(lc)
a.set_xlim(0,4*np.pi)
a.set_ylim(-1.1,1.1)
fig.show()
```


Question: Is it possible to control matplotlib marker orientation? If I have a triangular marker, is it possible to control its orientation? I have a series of facets, with their corresponding vertices, and I would like to plot a basemap of them. I know it is straightforward script when using Mayavi and tvtk.PolyData. But since I'm dealing with maps and not 3D objects, things got a bit complicated. ps: for maps I'm using basemap tool.

Response:
You can create custom polygons using the keyword argument marker and passing it a tuple of 3 numbers (number of sides, style, rotation). To create a triangle you would use (3, 0, rotation), an example is shown below.
```
import matplotlib.pyplot as plt

x = [1,2,3]
for i in x:
    plt.plot(i, i, marker=(3, 0, i*90), markersize=20, linestyle='None')

plt.xlim([0,4])
plt.ylim([0,4])

plt.show()
```


Question:
seaborn scatterplot marker size for ALL markers I can't find out anywhere how to change the marker size on seaborn scatterplots. There is a size option listed in the documentation but it is only for when you want variable size across points. I want the same size for all points but larger than the default! I tried making a new column of integers in my dataframe and set that as the size, but it looks like the actual value doesn't matter, it changes the marker size on a relative basis, so in this case all the markers were still the same size as the default. Here's some code:
```py
ax = sns.scatterplot(x="Data Set Description", y="R Squared", data=mean_df)
plt.show()
```
I just tried something and it worked, not sure if it's the best method though. I added size=[1, 1, 1, 1, 1, 1] and sizes=(500, 500). So essentially I'm setting all sizes to be the same, and the range of sizes to be only at 500.

Response:
You can do so by giving a value to the s argument to change the marker size. Example:
```
ax = sns.scatterplot(x="Data Set Description", y="R Squared", data=mean_df, s=10)
```


Question:
matplotlib imshow(): how to animate? i found this wonderful short tutorial on animation: http://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/ however i cant produce an animated imshow() plot of same fashion. I tried to replace some lines:
```
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 10), ylim=(0, 10))
#line, = ax.plot([], [], lw=2)
a=np.random.random((5,5))
im=plt.imshow(a,interpolation='none')
# initialization function: plot the background of each frame
def init():
    im.set_data(np.random.random((5,5)))
    return im

# animation function.  This is called sequentially
def animate(i):
    a=im.get_array()
    a=a*np.exp(-0.001*i)    # exponential decay of the values
    im.set_array(a)
    return im
```
but i run into errors can you help me get this running? thank you in advance. best,

Response:
You're very close, but there's one mistake - init and animate should return iterables containing the artists that are being animated. That's why in Jake's version they return line, (which is actually a tuple) rather than line (which is a single line object). Sadly the docs are not clear on this! You can fix your version like this:
```
# initialization function: plot the background of each frame
def init():
    im.set_data(np.random.random((5,5)))
    return [im]

# animation function.  This is called sequentially
def animate(i):
    a=im.get_array()
    a=a*np.exp(-0.001*i)    # exponential decay of the values
    im.set_array(a)
    return [im]
```


Question:
Pandas histogram df.hist() group by How to plot a histogram with pandas DataFrame.hist() using group by? I have a data frame with 5 columns: "A", "B", "C", "D" and "Group" There are two Groups classes: "yes" and "no" Using:
```
df.hist()
```
I get the hist for each of the 4 columns. Now I would like to get the same 4 graphs but with blue bars (group="yes") and red bars (group = "no"). I tried this withouth success:
```
df.hist(by = "group")
```

Response:
Using Seaborn If you are open to use Seaborn, a plot with multiple subplots and multiple variables within each subplot can easily be made using seaborn.FacetGrid.
```
import numpy as np; np.random.seed(1)
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.DataFrame(np.random.randn(300,4), columns=list("ABCD"))
df["group"] = np.random.choice(["yes", "no"], p=[0.32,0.68],size=300)

df2 = pd.melt(df, id_vars='group', value_vars=list("ABCD"), value_name='value')

bins=np.linspace(df2.value.min(), df2.value.max(), 10)
g = sns.FacetGrid(df2, col="variable", hue="group", palette="Set1", col_wrap=2)
g.map(plt.hist, 'value', bins=bins, ec="k")

g.axes[-1].legend()
plt.show()
```


Question: How to create a seaborn.heatmap() with frames around the tiles? I rendered a heatmap with seaborn.heatmap() works nicely. However, for a certain purpose I need frames around the plot. matplotlib.rcParams['axes.edgecolor'] = 'black' matplotlib.rcParams['axes.linewidth'] = 1 both don't work.

Response: sns.heatmap(dataset, linewidths=1, linecolor='black')


Question: How do I extend the margin at the bottom of a figure in Matplotlib? The following screenshot shows my x-axis. I added some labels and rotated them by 90 degrees in order to better read them. However, pyplot truncates the bottom such that I'm not able to completely read the labels. How do I extend the bottom margin in order to see the complete labels?

Response:
Two retroactive ways:
```py
fig, ax = plt.subplots()
# ...
fig.tight_layout()
```
Or
```py
fig.subplots_adjust(bottom=0.2) # or whatever
```
Here's a subplots_adjust example: http://matplotlib.org/examples/pylab_examples/subplots_adjust.html (but I prefer tight_layout)


Question:
Top label for matplotlib colorbars By default, matplotlib would position colorbar labels alongside the vertical colorbars. What is the best way to force the label to be on top of a colorbar? Currently my solution needs adjusting labelpad and y values depending on size of the label:
```py
import numpy as np
import matplotlib.pylab as plt

dat = np.random.randn(10,10)
plt.imshow(dat, interpolation='none')

clb = plt.colorbar()
clb.set_label('label', labelpad=-40, y=1.05, rotation=0)

plt.show()
```
Is there a better, more generic way to do this?

Response:
You could set the title of the colorbar axis (which appears above the axis), rather than the label (which appears along the long axis). To access the colorbar's Axes, you can use clb.ax. You can then use set_title, in the same way you can for any other Axes instance. For example:
```
import numpy as np
import matplotlib.pylab as plt

dat = np.random.randn(10,10)
plt.imshow(dat, interpolation='none')

clb = plt.colorbar()
clb.ax.set_title('This is a title')

plt.show()
```


Question: Giving graphs a subtitle I want to give my graph a title in big 18pt font, then a subtitle below it in smaller 10pt font. How can I do this in matplotlib? It appears the title() function only takes one single string with a single fontsize attribute. There has to be a way to do this, but how?

Response: What I do is use the title() function for the subtitle and the suptitle() for the main title (they can take different font size arguments).


Question:
yaxis range display using absolute values rather than offset values I have the following range of numpy data (deltas of usec timestamps):
```
array([ 4.312,  4.317,  4.316,  4.32 ,  4.316,  4.316,  4.319,  4.317,
    4.317,  4.316,  4.318,  4.316,  4.318,  4.316,  4.318,  4.317,
    4.317,  4.317,  4.316,  4.317,  4.318,  4.316,  4.318,  4.316,
    4.318,  4.316,  4.317,  4.317,  4.318,  4.316,  4.317,  4.317,
    4.317,  4.317,  4.317,  4.316,  4.319,  4.315,  4.319,  4.315,
    4.319,  4.315,  4.316,  4.319,  4.317,  4.317,  4.317,  4.318,
    4.315,  4.317,  4.317,  4.317,  4.319,  4.314,  4.32 ,  4.315,
    4.317,  4.318,  4.315,  4.318,  4.317,  4.317,  4.317,  4.316,
    4.317,  4.318,  4.317,  4.317,  4.317,  4.315,  4.319,  4.317,
    4.315,  4.319,  4.316,  4.318,  4.318,  4.315,  4.318,  4.317,
    4.317,  4.321])
```
When I plot with matplotlib.pyplot:
```
import matplotlib.pyplot as plt
 plt.plot( deltas )
 plt.show()
```
I get the following plot. Why is the Y-axis being scaled that way? How can I get the Y-axis to be labeled as the data, not an offset of the data? Sometimes the plot is the "+4.nnn" sometimes it isn't (depending on the data range?). Plotted "strangely": Plotted "correctly":

Response:
set useOffset to False:
```
ax = plt.gca()
ax.ticklabel_format(useOffset=False)
```


Question:
Grouping boxplots in seaborn when input is a DataFrame I intend to plot multiple columns in a pandas dataframe, all grouped by another column using groupby inside seaborn.boxplot. There is a nice answer here, for a similar problem in matplotlib matplotlib: Group boxplots but given the fact that seaborn.boxplot comes with groupby option I thought it could be much easier to do this in seaborn. Here we go with a reproducible example that fails:
```
import seaborn as sns
import pandas as pd
df = pd.DataFrame([[2, 4, 5, 6, 1], [4, 5, 6, 7, 2], [5, 4, 5, 5, 1],
                   [10, 4, 7, 8, 2], [9, 3, 4, 6, 2], [3, 3, 4, 4, 1]],
                  columns=['a1', 'a2', 'a3', 'a4', 'b'])

# display(df)
   a1  a2  a3  a4  b
0   2   4   5   6  1
1   4   5   6   7  2
2   5   4   5   5  1
3  10   4   7   8  2
4   9   3   4   6  2
5   3   3   4   4  1

#Plotting by seaborn
sns.boxplot(df[['a1','a2', 'a3', 'a4']], groupby=df.b)
```
What I get is something that completely ignores groupby option: Whereas if I do this with one column it works thanks to another SO question Seaborn groupby pandas Series :
```
sns.boxplot(df.a1, groupby=df.b)
```
So I would like to get all my columns in one plot (all columns come in a similar scale). EDIT: The above SO question was edited and now includes a 'not clean' answer to this problem, but it would be nice if someone has a better idea for this problem.

Response:
As the other answers note, the boxplot function is limited to plotting a single "layer" of boxplots, and the groupby parameter only has an effect when the input is a Series and you have a second variable you want to use to bin the observations into each box.. However, you can accomplish what I think you're hoping for with the factorplot function, using kind="box". But, you'll first have to "melt" the sample dataframe into what is called long-form or "tidy" format where each column is a variable and each row is an observation:
```
df_long = pd.melt(df, "b", var_name="a", value_name="c")
```
Then it's very simple to plot:
```
sns.factorplot("a", hue="b", y="c", data=df_long, kind="box")
```


Question:
Plot two histograms on single chart I created a histogram plot using data from a file and no problem. Now I wanted to superpose data from another file in the same histogram, so I do something like this
```
n,bins,patchs = ax.hist(mydata1,100)
n,bins,patchs = ax.hist(mydata2,100)
```
but the problem is that for each interval, only the bar with the highest value appears, and the other is hidden. I wonder how could I plot both histograms at the same time with different colors.

Response:
Here you have a working example:
```
import random
import numpy
from matplotlib import pyplot

x = [random.gauss(3,1) for _ in range(400)]
y = [random.gauss(4,2) for _ in range(400)]

bins = numpy.linspace(-10, 10, 100)

pyplot.hist(x, bins, alpha=0.5, label='x')
pyplot.hist(y, bins, alpha=0.5, label='y')
pyplot.legend(loc='upper right')
pyplot.show()
```


Question:
Why do many examples use `fig, ax = plt.subplots()` I'm learning to use matplotlib by studying examples, and a lot of examples seem to include a line like the following before creating a single plot...
```
fig, ax = plt.subplots()
```
Here are some examples... Modify tick label text http://matplotlib.org/examples/pylab_examples/boxplot_demo2.html I see this function used a lot, even though the example is only attempting to create a single chart. Is there some other advantage? The official demo for subplots() also uses f, ax = subplots when creating a single chart, and it only ever references ax after that. This is the code they use.
```
# Just a figure and one subplot
f, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')
```

Response:
plt.subplots() is a function that returns a tuple containing a figure and axes object(s). Thus when using fig, ax = plt.subplots() you unpack this tuple into the variables fig and ax. Having fig is useful if you want to change figure-level attributes or save the figure as an image file later (e.g. with fig.savefig('yourfilename.png')). You certainly don't have to use the returned figure object but many people do use it later so it's common to see. Also, all axes objects (the objects that have plotting methods), have a parent figure object anyway, thus:
```
fig, ax = plt.subplots()
```
is more concise than this:
```
fig = plt.figure()
ax = fig.add_subplot(111)
```


Question:
How to retrieve colorbar instance from figure in matplotlib all. I want to update the colorbar of a figure when the imagedata is changed. So something like:
```
img = misc.lena()
fig = plt.figure()
ax = plt.imshow(im)
plt.colorbar(ax)
newimg = img+10*np.randn(512,512)

def update_colorbar(fig,ax,newimg):
    cbar = fig.axes[1]
    ax.set_data(newimg)
    cbar.update_normal(ax)
    plt.draw()
```
but it seems that returned results from fig.axes() does not have the colorbar instance like I expected. I can probably just pass the colorbar instance as an argument to the update function, but I thought just passing one fig parameter may be good enough. Can anyone explain a little bit on how to retrieve the colorbar from the figure? Or why 'fig.axes()' doesn't return the AxesImage or Colobar instance but just the Axes or AxesSubplot? I think I just need more understanding of the Axes/Figure stuff.Thank you!

Response:
Sometimes it can be useful to retrieve a colorbar even if it was not held in a variable. In this case, it is possible to retrieve the colorbar from the plot with:
```
# Create an example image and colourbar
img = np.arange(20).reshape(5,4)
plt.imshow(img)
plt.colorbar()

# Get the current axis
ax = plt.gca()

# Get the images on an axis
im = ax.images

# Assume colorbar was plotted last one plotted last
cb = im[-1].colorbar

# Do any actions on the colorbar object (e.g. remove it)
cb.remove()
```
EDIT: or, equivalently, the one liner:
```
plt.gca().images[-1].colorbar.remove()
```
N.B.: see also comments for the use of ax.collections[-1] instead of ax.images[-1]. For me it always worked only the first way, I don't know what depends on, maybe the type of data or plot. Now you can operate on cb as if it were stored using commands described in the colorbar API. For instance you could change xlim or call update as explained in other comments. You could remove it with cb.remove() and recreate it with plt.colorbar(). plt.draw() or show should be called after to update plot. As the image is the mappable associated to the colorbar and can be obtained with cb.mappable.


Question:
How to plot statsmodels linear regression (OLS) cleanly Problem Statement: I have some nice data in a pandas dataframe. I'd like to run simple linear regression on it: Using statsmodels, I perform my regression. Now, how do I get my plot? I've tried statsmodels' plot_fit method, but the plot is a little funky: I was hoping to get a horizontal line which represents the actual result of the regression. Statsmodels has a variety of methods for plotting regression (a few more details about them here) but none of them seem to be the super simple "just plot the regression line on top of your data" -- plot_fit seems to be the closest thing. Questions: The first picture above is from pandas' plot function, which returns a matplotlib.axes._subplots.AxesSubplot. Can I overlay a regression line easily onto that plot? Is there a function in statsmodels I've overlooked? Is there a better way to put together this figure? Two related questions: Plotting Pandas OLS linear regression results Getting the regression line to plot from a Pandas regression Neither seems to have a good answer. Sample data
```none
motifScore  expression
6870    1.401123    0.55
10456   1.188554    -1.58
12455   1.476361    -1.75
18052   1.805736    0.13
19725   1.110953    2.30
30401   1.744645    -0.49
30716   1.098253    -1.59
30771   1.098253    -2.04
```
abline_plot I had tried this, but it doesn't seem to work... not sure why:

Response:
As I mentioned in the comments, seaborn is a great choice for statistical data visualization.
```
import seaborn as sns

sns.regplot(x='motifScore', y='expression', data=motif)
```
Alternatively, you can use statsmodels.regression.linear_model.OLS and manually plot a regression line.
```
import statsmodels.api as sm

# regress "expression" onto "motifScore" (plus an intercept)
model = sm.OLS(motif.expression, sm.add_constant(motif.motifScore))
p = model.fit().params

# generate x-values for your regression line (two is sufficient)
x = np.arange(1, 3)

# scatter-plot data
ax = motif.plot(x='motifScore', y='expression', kind='scatter')

# plot regression line on the same axes, set x-axis limits
ax.plot(x, p.const + p.motifScore * x)
ax.set_xlim([1, 2])
```
Yet another solution is statsmodels.graphics.regressionplots.abline_plot which takes away some of the boilerplate from the above approach.
```
import statsmodels.api as sm
from statsmodels.graphics.regressionplots import abline_plot

# regress "expression" onto "motifScore" (plus an intercept)
model = sm.OLS(motif.expression, sm.add_constant(motif.motifScore))

# scatter-plot data
ax = motif.plot(x='motifScore', y='expression', kind='scatter')

# plot regression line
abline_plot(model_results=model.fit(), ax=ax)
```


Question:
How is order of items in matplotlib legend determined? I am having to reorder items in a legend, when I don't think I should have to. I try:
```
from pylab import *
clf()
ax=gca()
ht=ax.add_patch(Rectangle((1,1),1,1,color='r',label='Top',alpha=.1))
h1=ax.bar(1,2,label='Middle')
hb=ax.add_patch(Rectangle((1,1),1,1,color='k',label='Bottom',alpha=.11))
legend()
show()
```
and end up with Bottom above Middle. How can I get the right order? Is it not determined by creation order? Update: The following can be used to force the order. I think this may be the simplest way to do it, and that seems awkward. The question is what determines the original order?
```
hh=[ht,h1,hb]
legend([ht,h1.patches[0],hb],[H.get_label() for H in hh])
```

Response:
A slight variation on some other aswers. The list order should have the same length as the number of legend items, and specifies the new order manually.
```
handles, labels = plt.gca().get_legend_handles_labels()
order = [0,2,1]
plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order])
```


Question:
How to find the intersection of two graphs Let 0 <= x <= 1. I have two columns f and g of length 5000 respectively. Now I plot:
```
plt.plot(x, f, '-')
plt.plot(x, g, '*')
```
I want to find the point 'x' where the curve intersects. I don't want to find the intersection of f and g. I can do it simply with:
```
set(f) & set(g)
```

Response:
You can use np.sign in combination with np.diff and np.argwhere to obtain the indices of points where the lines cross (in this case, the points are [ 0, 149, 331, 448, 664, 743]):
```
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 1000)
f = np.arange(0, 1000)
g = np.sin(np.arange(0, 10, 0.01) * 2) * 1000

plt.plot(x, f, '-')
plt.plot(x, g, '-')

idx = np.argwhere(np.diff(np.sign(f - g))).flatten()
plt.plot(x[idx], f[idx], 'ro')
plt.show()
```
First it calculates f - g and the corresponding signs using np.sign. Applying np.diff reveals all the positions, where the sign changes (e.g. the lines cross). Using np.argwhere gives us the exact indices.


Question:
Need to add space between SubPlots for X axis label, maybe remove labelling of axis notches Looking to add in vertical space between plotted graphs to allow a X-Axis label to show: Each graph needs to have space to show the day, currently the last 2 graphs are the only one's that show simply because the graphs are overlapping it. Also curious if I could actually remove the notch labels for the X-Axis for the graphs above the one's marked Thursday/Friday, i.e. the bottom X-axis is the only one that shows. Same for the Y-Axis, but only the graphs on the left having the scale shown. *Unfortunately I can't post an image to show this since I don't have enough rep. Code snippet:
```
import mathlib.pyplot as pyplot
fig = pyplot.figure()
ax1 = fig.add_subplot(4,2,1)
ax1.set_yscale('log')
ax2 = fig.add_subplot(4,2,2, sharex=ax1, sharey=ax1)
ax3 = fig.add_subplot(4,2,3, sharex=ax2, sharey=ax2)
ax4 = fig.add_subplot(4,2,4, sharex=ax3, sharey=ax3)
ax5 = fig.add_subplot(4,2,5, sharex=ax4, sharey=ax4)
ax6 = fig.add_subplot(4,2,6, sharex=ax5, sharey=ax5)
ax7 = fig.add_subplot(4,2,7, sharex=ax6, sharey=ax6)
ax1.plot(no_dict["Saturday"],'k.-',label='Saturday')
ax1.set_xlabel('Saturday')
ax1.axis([0,24,0,10000])
pyplot.suptitle('Title')
pyplot.xlabel('Hour in 24 Hour Format')
ax2.plot(no_dict["Sunday"],'b.-',label='Sunday')
ax2.set_xlabel('Sunday')
...
```

Response:
Use subplots_adjust. In your case this looks good:
```
fig.subplots_adjust(hspace=.5)
```
to remove the tick labels do this:
```
ax1.set_xticklabels([])
```
Similar for the yticklabels. However, you cannot share the x-axis with the plots that do have tick labels.


Question:
Matplotlib scatter plot with unknown error I am attempting to create a scatter plot. I have a list of numbers from 0 - 17 as well as an array with 18 values. I can plot the data as a line plot but when I try to plot as a scatter, I get an error message I do not understand:
```none
TypeError: ufunc 'sqrt' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
```
What does this error message mean and how can I get the data to plot as a scatter?
```py
import numpy as np
import matplotlib.pyplot as plt

y = [7316.0, 7453.25, 7518.25, 7711.5, 7448.0, 7210.25, 7416.75, 6960.75,
     7397.75, 6397.5, 5522.75, 5139.0, 5034.75, 4264.75, 5106.0, 3489.5,
     4712.0, 4770.0]
x = np.arange(0,18,1)

plt.rcParams['legend.loc'] = 'best'
plt.figure(1)
plt.xlim(0, 20)
plt.ylim(0, 10000)
plt.scatter(x, y, 'r')
plt.show()
```

Response:
Check the scatter documentation. Third argument is for size of points and should be scalar or array_like. I assume 'r' is for color so do the following:
```
plt.scatter(x, y, c='r')
```


Question:
Unable to show legend in seaborn distplot I am new to plotting in python and trying following code to plot distribution in seaborn but unable to see the legend, i.e., test_label1 and test_label1 on the plot.
```
import matplotlib.pylab as plt
import seaborn as sns
import numpy as np

plt.figure("Test Plots")
lst1 = list(np.random.rand(10))
lst2 = list(np.random.rand(10))
sns.distplot(lst1, label='test_label1', color="0.25")
sns.distplot(lst2, label='test_label2', color="0.25")

plt.show()
```

Response: As you have already labelled your plots using label= inside your sns.distplot then all you have to do is show your legend. This is done by adding plt.legend() just before plt.show() More information on matplotlib legends can be found in the documentation


Question: How do I let my matplotlib plot go beyond the axes? I have to translate an image plotting script from matlab to matplotlib/pylab, and I'm trying to achieve the same effect as the matlab image below: As you can see, the z order of the plots seem to be higher than the z order of the grid, so the markers are not hidden by the axes. However, I can't figure out a way to do the same with my matplotlib image: I'm wondering if it is possible to get the same display without having to increase the limits of the y axis.

Response:
To get the marker to show beyond the axes you can turn the clipping off. This can be done using the keyword argument in the plot command clip_on=False. For example:
```
import matplotlib.pyplot as plt
plt.plot(range(5), range(5), 'ro', markersize=20, clip_on=False, zorder=100)
plt.show()
```


Question:
AtributeError: 'module' object has no attribute 'plt' - Seaborn I'm very new with these libraries and i'm having troubles while plotting this:
```
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import random

df5 = pd.read_csv('../../../../datos/tiempos-exacto-variando-n-m0.csv', sep=', ', engine='python')
print(df5)
df5['n'] = df5['n'].apply(lambda x: x**2)
sns.jointplot(df5['n'], df5['tiempoTotal'], kind="reg")
sns.plt.show()
```
And i'm getting this output:
```
n  m  tiempoTotal
0      1  0         2274
1      2  0         3370
2      3  0         5709
3      4  0         8959
4      5  0        13354
5      6  0        18503
6      7  0        26329
7      8  0        33859
8      9  0        41110
9     10  0        52710
10    11  0        64364
11    12  0        74142
12    13  0        81072
13    14  0        69332
14    15  0        71027
15    16  0        89721
16    17  0        85459
17    18  0        95217
18    19  0       119210
19    20  0       136888
20    21  0       131903
21    22  0       138395
22    23  0       151222
23    24  0       163542
24    25  0       177236
25    26  0       192475
26    27  0       240162
27    28  0       260701
28    29  0       235752
29    30  0       250835
..   ... ..          ...
580  581  0     88306854
581  582  0     89276420
582  583  0     87457875
583  584  0     90807004
584  585  0     87790003
585  586  0     89821530
586  587  0     89486585
587  588  0     88496901
588  589  0     89090661
589  590  0     89110803
590  591  0     90397942
591  592  0     94029839
592  593  0     92749859
593  594  0    105991135
594  595  0     95383921
595  596  0    105155207
596  597  0    114193414
597  598  0     98108892
598  599  0     97888966
599  600  0    103802453
600  601  0     97249346
601  602  0    101917488
602  603  0    104943847
603  604  0     98966140
604  605  0     97924262
605  606  0     97379587
606  607  0     97518808
607  608  0     99839892
608  609  0    100046492
609  610  0    103857464

[610 rows x 3 columns]
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-21-63146953b89d> in <module>()
      9 df5['n'] = df5['n'].apply(lambda x: x**2)
     10 sns.jointplot(df5['n'], df5['tiempoTotal'], kind="reg")
---> 11 sns.plt.show()

AttributeError: 'module' object has no attribute 'plt'
```
I'm running this in my Jupyter Notebook with Python 2.7.12. Any ideas?

Response: sns.plt.show() works fine for me using seaborn 0.7.1. Could be that this is different in other versions. However, if you anyways import matplotlib.pyplot as plt you may as well simply use plt.show(), as sns.plt.show() is only working because pyplot is available inside the seaborn namespace.


Question:
Create own colormap using matplotlib and plot color scale I have the following problem, I want to create my own colormap (red-mix-violet-mix-blue) that maps to values between -2 and +2 and want to use it to color points in my plot. The plot should then have the colorscale to the right. That is how I create the map so far. But I am not really sure if it mixes the colors.
```
cmap = matplotlib.colors.ListedColormap(["red","violet","blue"], name='from_list', N=None)
m = cm.ScalarMappable(norm=norm, cmap=cmap)
```
That way I map the colors to the values.
```
colors = itertools.cycle([m.to_rgba(1.22), ..])
```
Then I plot it:
```
for i in range(0, len(array_dg)):
  plt.plot(array_dg[i], markers.next(),alpha=alpha[i], c=colors.next())
```
My problems are: 1. I can't plot the color scale. 2. I am not completely sure if my scale is creating a continues (smooth) colorscale.

Response:
Since the methods used in other answers seems quite complicated for such easy task, here is a new answer: Instead of a ListedColormap, which produces a discrete colormap, you may use a LinearSegmentedColormap. This can easily be created from a list using the from_list method.
```
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors

x,y,c = zip(*np.random.rand(30,3)*4-2)

norm=plt.Normalize(-2,2)
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", ["red","violet","blue"])

plt.scatter(x,y,c=c, cmap=cmap, norm=norm)
plt.colorbar()
plt.show()
```
More generally, if you have a list of values (e.g. [-2., -1, 2]) and corresponding colors, (e.g. ["red","violet","blue"]), such that the nth value should correspond to the nth color, you can normalize the values and supply them as tuples to the from_list method.
```
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors

x,y,c = zip(*np.random.rand(30,3)*4-2)

cvals  = [-2., -1, 2]
colors = ["red","violet","blue"]

norm=plt.Normalize(min(cvals),max(cvals))
tuples = list(zip(map(norm,cvals), colors))
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", tuples)

plt.scatter(x,y,c=c, cmap=cmap, norm=norm)
plt.colorbar()
plt.show()
```


Question: How to get center of set of points using Python I would like to get the center point(x,y) of a figure created by a set of points. How do I do this?

Response:
If you mean centroid, you just get the average of all the points.
```
x = [p[0] for p in points]
y = [p[1] for p in points]
centroid = (sum(x) / len(points), sum(y) / len(points))
```


Question:
Simple line plots using seaborn I'm trying to plot a ROC curve using seaborn (python). With matplotlib I simply use the function plot:
```
plt.plot(one_minus_specificity, sensitivity, 'bs--')
```
where one_minus_specificity and sensitivity are two lists of paired values. Is there a simple counterparts of the plot function in seaborn? I had a look at the gallery but I didn't find any straightforward method.

Response:
Since seaborn also uses matplotlib to do its plotting you can easily combine the two. If you only want to adopt the styling of seaborn the set_style function should get you started:
```
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

sns.set_style("darkgrid")
plt.plot(np.cumsum(np.random.randn(1000,1)))
plt.show()
```
Result:


Question:
How can one display an image using cv2 in Python I've been working with code to display frames from a movie. The bare bones of the code is as follows:
```
import cv2
import matplotlib.pyplot as plt

# Read single frame avi
cap = cv2.VideoCapture('singleFrame.avi')
rval, frame = cap.read()

# Attempt to display using cv2 (doesn't work)
cv2.namedWindow("Input")
cv2.imshow("Input", frame)

#Display image using matplotlib (Works)
b,g,r = cv2.split(frame)
frame_rgb = cv2.merge((r,g,b))
plt.imshow(frame_rgb)
plt.title('Matplotlib') #Give this plot a title,
                        #so I know it's from matplotlib and not cv2
plt.show()
```
Because I can display the image using matplotlib, I know that I'm successfully reading it in. I don't understand why my creation of a window and attempt to show an image using cv2 doesn't work. No cv2 window ever appears. Oddly though, if I create a second cv2 window, the 'input' window appears, but it is only a blank/white window. What am I missing here?

Response:
As far as I can see, you are doing it almost good. There is one thing missing:
```
cv2.imshow('image',img)
cv2.waitKey(0)
```
So probably your window appears but is closed very very fast.


Question: Annotating a 3D scatter plot I'm trying to generate a 3D scatter plot using Matplotlib. I would like to annotate individual points like the 2D case here: How to put individual tags for a matplotlib scatter plot?. I've tried to use this function and consulted the Matplotlib docoment but found it seems that the library does not support 3D annotation. Does anyone know how to do this?

Response:
Maybe easier via ax.text(...):
```
from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
from numpy.random import rand
from pylab import figure

m=rand(3,3) # m is an array of (x,y,z) coordinate triplets

fig = figure()
ax = fig.add_subplot(projection='3d')

for i in range(len(m)): #plot each point + it's index as text above
    ax.scatter(m[i,0],m[i,1],m[i,2],color='b')
    ax.text(m[i,0],m[i,1],m[i,2],  '%s' % (str(i)), size=20, zorder=1,
    color='k')

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


Question:
Matplotlib: Save figure as file from iPython notebook I am trying to save a Matplotlib figure as a file from an iPython notebook.
```
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_axes([1,1,1,1])
ax.plot([1,2])

fig.savefig('test.png')
```
The inline view in the iPython notebook looks good: The file 'test.png' is almost empty though. It looks like the plot is shifted to the top right, you can see the tick labels '1.0' and '0.0' in the corner. How can I produce a file from the iPython notebook that looks like the inline view?

Response:
Problem solved: add 'bbox_inches='tight' argument to savefig.
```
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_axes([1,1,1,1])
plt.plot([1,2])

savefig('test.png', bbox_inches='tight')
```
I don't understand what's happening here, but the file looks like the iPython notebook inline file now. Yay.


Question:
Annotate bars with values on Pandas bar plots I was looking for a way to annotate my bars in a Pandas bar plot with the rounded numerical values from my DataFrame.
```

```python
df=pd.DataFrame({'A':np.random.rand(2),'B':np.random.rand(2)},index=['value1','value2'] )
```

```python
df
#Output
#                 A         B
#  value1  0.440922  0.911800
#  value2  0.588242  0.797366
#```
#I would like to get something like this: I tried with this code sample, but the annotations are all centered on the x ticks:
#```
```

```python
ax = df.plot(kind='bar')
```

```python
for idx, label in enumerate(list(df.index)):
#Output
#        for acc in df.columns:
#            value = np.round(df.ix[idx][acc],decimals=2)
#            ax.annotate(value,
#                        (idx, value),
#                         xytext=(0, 15),
#                         textcoords='offset points')
#```
```

Response:
You get it directly from the axes' patches:
```
for p in ax.patches:
    ax.annotate(str(p.get_height()), (p.get_x() * 1.005, p.get_height() * 1.005))
```
You'll want to tweak the string formatting and the offsets to get things centered, maybe use the width from p.get_width(), but that should get you started. It may not work with stacked bar plots unless you track the offsets somewhere.


Question:
matplotlib: Aligning y-axis labels in stacked scatter plots In the plot bellow i have two scatter plots which have different number scale, so their Y-axis labels are not aligned. Is there any way I can force the horizontal alignment in the y-axis labels?
```
import matplotlib.pylab as plt
import random
import matplotlib.gridspec as gridspec

random.seed(20)
data1 = [random.random() for i in range(10)]
data2 = [random.random()*1000 for i in range(10)]

gs = gridspec.GridSpec(2,1)
fig = plt.figure()

ax = fig.add_subplot(gs[0])
ax.plot(data1)
ax.set_ylabel(r'Label One', size =16)

ax = fig.add_subplot(gs[1])
ax.plot(data2)
ax.set_ylabel(r'Label Two', size =16)

plt.show()
```

Response:
You can use the set_label_coords method.
```
import matplotlib.pylab as plt
import random
import matplotlib.gridspec as gridspec

random.seed(20)
data1 = [random.random() for i in range(10)]
data2 = [random.random()*1000 for i in range(10)]

gs = gridspec.GridSpec(2,1)
fig = plt.figure()

ax = fig.add_subplot(gs[0])
ax.plot(data1)
ax.set_ylabel(r'Label One', size =16)
ax.get_yaxis().set_label_coords(-0.1,0.5)

ax = fig.add_subplot(gs[1])
ax.plot(data2)
ax.set_ylabel(r'Label Two', size =16)
ax.get_yaxis().set_label_coords(-0.1,0.5)
```


Question: How to modify the navigation toolbar easily in a matplotlib figure window? Is it possible to do something like the following to modify the navigation toolbar in matplotlib? Generate a figure window, with: fig = figure() Get a reference of the navigation tool-bar, with: tbar = fig.get_navigation_toolbar(), or better yet, just by: tbar = fig.navtbar Modify the tool-bar through the reference tbar, such as delete/add/edit a button with something like this: tbar.add_button(); tbar.remove_button(a reference to a button); tbar.edit_button(a reference to a button); Update the figure with: fig.canvas.draw() Thank you very much.

Response:
The way I found to remove unwanted toolbar items is making a subclass, which is instantiated and used in a GTK application. As I manually create Figure, FigureCanvas and NavigationToolbar objects anyway, this was the easiest way.
```
class NavigationToolbar(NavigationToolbar2GTKAgg):
    # only display the buttons we need
    toolitems = [t for t in NavigationToolbar2GTKAgg.toolitems if
                 t[0] in ('Home', 'Pan', 'Zoom', 'Save')]
```
If you want to create custom buttons, you should take a look on the definition of NavigationToolbar2 in backend_bases. You can easily add your own entries to the toolitems list and define appropriate callback functions in your toolbar subclass.


Question:
Matplotlib DateFormatter for axis label not working I'm trying to adjust the formatting of the date tick labels of the x-axis so that it only shows the Year and Month values. From what I've found online, I have to use mdates.DateFormatter, but it's not taking effect at all with my current code as is. Anyone see where the issue is? (the dates are the index of the pandas Dataframe)
```
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import pandas as pd

fig = plt.figure(figsize = (10,6))
ax = fig.add_subplot(111)

ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))

basicDF['some_column'].plot(ax=ax, kind='bar', rot=75)

ax.xaxis_date()
```
Reproducible scenario code:
```
import numpy as np
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import pandas as pd

rng = pd.date_range('1/1/2014', periods=20, freq='m')

blah = pd.DataFrame(data = np.random.randn(len(rng)), index=rng)

fig = plt.figure(figsize = (10,6))
ax = fig.add_subplot(111)

ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))

blah.plot(ax=ax, kind='bar')

ax.xaxis_date()
```
Still can't get just the year and month to show up. If I set the format after .plot , get an error like this: ValueError: DateFormatter found a value of x=0, which is an illegal date. This usually occurs because you have not informed the axis that it is plotting dates, e.g., with ax.xaxis_date(). It's the same for if I put it before ax.xaxis_date() or after.

Response:
pandas just doesn't work well with custom date-time formats. You need to just use raw matplotlib in cases like this.
```
import numpy
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas

N = 20
numpy.random.seed(N)

dates = pandas.date_range('1/1/2014', periods=N, freq='m')
df = pandas.DataFrame(
    data=numpy.random.randn(N),
    index=dates,
    columns=['A']
)

fig, ax = plt.subplots(figsize=(10, 6))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
ax.bar(df.index, df['A'], width=25, align='center')
```
And that gives me:


Question:
Improve subplot size/spacing with many subplots I need to generate a whole bunch of vertically-stacked plots in matplotlib. The result will be saved using savefig and viewed on a webpage, so I don't care how tall the final image is, as long as the subplots are spaced so they don't overlap. No matter how big I allow the figure to be, the subplots always seem to overlap. My code currently looks like
```
import matplotlib.pyplot as plt
import my_other_module

titles, x_lists, y_lists = my_other_module.get_data()

fig = plt.figure(figsize=(10,60))
for i, y_list in enumerate(y_lists):
    plt.subplot(len(titles), 1, i)
    plt.xlabel("Some X label")
    plt.ylabel("Some Y label")
    plt.title(titles[i])
    plt.plot(x_lists[i],y_list)
fig.savefig('out.png', dpi=100)
```

Response:
Please review matplotlib: Tight Layout guide and try using matplotlib.pyplot.tight_layout, or matplotlib.figure.Figure.tight_layout As a quick example:
```
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=4, ncols=4, figsize=(8, 8))
fig.tight_layout() # Or equivalently,  "plt.tight_layout()"

plt.show()
```
Without Tight Layout With Tight Layout


Question:
How to set color in matplotlib histograms I am plotting a histogram using Matplotlib. I would like the color of the histogram to be "sky blue". But the data overlaps, and produces a histogram which is nearly black in color.
```py
plt.hist(data, color = "skyblue")
```
Below is how the histogram looks. As you can see, even though I specified the color to be "Skyblue, the histogram on the right is nearly black.

Response:
The reason for the histogram to look black is that the bars' surrounding lines (which are black) take most of the space. Options would be to get rid of the edges by setting the linewidth to zero:
```
plt.hist(data, color = "skyblue", lw=0)
```
and/or to set the edgecolor to the same color as the bars itself
```
plt.hist(data, color = "skyblue", ec="skyblue")
```


Question:
Change values on matplotlib imshow() graph axis Say I have some input data:
```py
data = np.random.normal(loc=100, scale=10, size=(500,1,32))
hist = np.ones((32, 20)) # initialise hist
for z in range(32):
    hist[z], edges = np.histogram(data[:, 0, z], bins=np.arange(80, 122, 2))
```
I can plot it using imshow():
```py
plt.imshow(hist, cmap='Reds')
```
getting: However, the x-axis values do not match the input data (i.e. mean of 100, range from 80 to 122). Therefore, I'd like to change the x-axis to show the values in edges. I have tried:
```py
ax = plt.gca()
ax.set_xlabel([80,122]) # range of values in edges
...
# this shifts the plot so that nothing is visible
```
and
```py
ax.set_xticklabels(edges)
...
# this labels the axis but does not centre around the mean:
```
Any ideas on how I can change the axis values to reflect the input data I am using?

Response:
I would try to avoid changing the xticklabels if possible, otherwise it can get very confusing if you for example overplot your histogram with additional data. Defining the range of your grid is probably the best and with imshow it can be done by adding the extent keyword. This way the axes gets adjusted automatically. If you want to change the labels i would use set_xticks with perhaps some formatter. Altering the labels directly should be the last resort.
```
fig, ax = plt.subplots(figsize=(6,6))

ax.imshow(hist, cmap=plt.cm.Reds, interpolation='none', extent=[80,120,32,0])
ax.set_aspect(2) # you may also use am.imshow(..., aspect="auto") to restore the aspect ratio
```


Question:
Python matplotlib decrease size of colorbar labels I need your help! I have a plotting code which is the following:
```
fig = plt.figure()
ax1 = fig.add_subplot(111)

imax1 = ax1.imshow(data,interpolation = 'nearest', origin = 'lower',cmap=cm.jet)#plot
cbar = plt.colorbar(imax1, extend='neither', spacing='proportional',
                orientation='vertical', shrink=0.7, format="%.0f")
cbar.set_label(r"ET [mm/month]", size=10)

titlestr = "Evapotranspiration in mm/month"
plt.title(titlestr)
#plt.xlabel("Longitude")
#plt.ylabel("Latitude")
imax1.set_clim(0,60)
labels = [item.get_text() for item in ax1.get_xticklabels()]
for ii in range(np.shape(labels)[0]):
    labels[ii] = str(grid_lon[75*ii/np.shape(labels)[0]])

ax1.set_xticklabels(labels, rotation = 45, ha='right', size = 10)

labels = [item.get_text() for item in ax1.get_yticklabels()]
for ii in range(np.shape(labels)[0]):
    labels[ii] = str(grid_lat[75*ii/np.shape(labels)[0]])

ax1.set_yticklabels(labels, size = 10)

pngname = "./out/2d_"+variable+"_"+mm+".png"
print "save ", pngname
plt.savefig(pngname, dpi=None, facecolor='w', edgecolor='w',
    orientation='portrait', papertype=None, format=None,
    transparent=False, bbox_inches=None, pad_inches=0.1)

print "plot finished"
```
I would like to set the label size of the colorbar labels (e.g. 0,10,20,...60) to size of 10 or smaller. This will probably go into the line "imax1.set_clim(0,60). Any ideas? I'd be also interested to print information of the imax1 object to command line. How could I do that? E.g. available attributes and functions of imax1. I deeply appreciate your help!

Response:
Aha! Found the answer here:
```
cbar.ax.tick_params(labelsize=10)
```
P.S. Upvote that answer and give Paul some love!


Question:
How can I display a numpy array with imshow The np.array that results from this loop has 4383 lines and 6 columns. I have tried without success to use pylab.imshow() from matplotlib(pylab) to display the array. The objective is to create an image of the array, in which the colors gradient represent the magnitude of the array values. Each row of the array represents the variation in depth of a lake temperature in each day (4383 days). Thus the objective is to find differences in lake temperatures in depth and with time.
```py
TempLake = np.zeros((N+1,Nlayers))
TempLake[0] = T0

Q = np.zeros(N+1)
Q[0] = 0.0
for i in xrange(N):
    Q[i+1]=Qn(HSR[i],TD[i],FW[i],TempLake[i][0])
    TempLake[i+1] = main_loop(Z,z,Areat0,Areat1,TempLake[i],wind[i],Q[i],Q[i+1])

pylab.imshow(TempLake)
pylab.show()
```

Response:
You can use imshow as follows:
```
import pylab as plt
import numpy as np

Z=np.array(((1,2,3,4,5),(4,5,6,7,8),(7,8,9,10,11)))
im = plt.imshow(Z, cmap='hot')
plt.colorbar(im, orientation='horizontal')
plt.show()
```
In your case can you check the output of TempLake.


Question:
Seaborn Bar Plot Ordering I have a pandas dataframe that has two columns. I need the plot ordered by the "Count" Column.
```
dicti=({'37':99943,'25':47228,'36':16933,'40':14996,'35':11791,'34':8030,'24' : 6319 ,'2'  :5055 ,'39' :4758 ,'38' :4611  })
pd_df = pd.DataFrame(list(dicti.iteritems()))
pd_df.columns =["Dim","Count"]
plt.figure(figsize=(12,8))
ax = sns.barplot(x="Dim", y= "Count",data=pd_df )
ax.get_yaxis().set_major_formatter(plt.FuncFormatter(lambda x, loc: "
{:,}".format(int(x))))
ax.set(xlabel="Dim", ylabel='Count')
for item in ax.get_xticklabels():
    item.set_rotation(90)
for i, v in enumerate(pd_df["Count"].iteritems()):
    ax.text(i ,v[1], "{:,}".format(v[1]), color='m', va ='bottom',
    rotation=45)
plt.tight_layout()
```
Right now the plot is getting ordered by the "Dim" column, I need it ordered by the "Count" column,How can I do this?

Response:
you can use the order parameter for this.
```
sns.barplot(x='Id', y="Speed", data=df, order=result['Id'])
```
Credits to Wayne. See the rest of his code. This link is still working for me. But, for the sake of convenience, I'm pasting the author's code here.
```
result = df.groupby(["Id"])['Speed'].aggregate(np.median).reset_index().sort_values('Speed')
sns.barplot(x='Id', y="Speed", data=df, order=result['Id'])
plt.show()
```
df
```
Id  Speed
0   1     30
1   1     35
2   1     31
3   2     20
4   2     25
```
result
```
Id   Speed
1   2   22.5
0   1   31.0
2   3   80.0
```


Question:
Removing white space around a saved image I need to take an image and save it after some process. The figure looks fine when I display it, but after saving the figure, I got some white space around the saved image. I have tried the 'tight' option for savefig method, did not work either. The code:
```
import matplotlib.image as mpimg
import matplotlib.pyplot as plt

fig = plt.figure(1)
img = mpimg.imread("image.jpg")
plt.imshow(img)
ax = fig.add_subplot(1, 1, 1)

extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
plt.savefig('1.png', bbox_inches=extent)

plt.axis('off')
plt.show()
```
I am trying to draw a basic graph by using NetworkX on a figure and save it. I realized that without a graph it works, but when added a graph I get white space around the saved image;
```
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import networkx as nx

G = nx.Graph()
G.add_node(1)
G.add_node(2)
G.add_node(3)
G.add_edge(1, 3)
G.add_edge(1, 2)
pos = {1:[100, 120], 2:[200, 300], 3:[50, 75]}

fig = plt.figure(1)
img = mpimg.imread("image.jpg")
plt.imshow(img)
ax = fig.add_subplot(1, 1, 1)

nx.draw(G, pos=pos)

extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
plt.savefig('1.png', bbox_inches=extent)

plt.axis('off')
plt.show()
```

Response:
You can remove the white space padding by setting bbox_inches="tight" in savefig:
```
plt.savefig("test.png",bbox_inches='tight')
```
You'll have to put the argument to bbox_inches as a string, perhaps this is why it didn't work earlier for you. Possible duplicates: Matplotlib plots: removing axis, legends and white spaces How to set the margins for a matplotlib figure? Reduce left and right margins in matplotlib plot


Question:
How do I adjust (offset) colorbar title in matplotlib Given the following code:
```
imshow(np.arange(16*16).reshape(16,16))
cb = colorbar()
cb.set_label("Foo")
cb.set_ticks([0,255])
```
Which produces: How do I adjust the colorbar text "Foo" so that it is offset to the left, betwen the 0 and 255, closer to the colorbar, reducing the un-needed whitespace?

Response:
```
cb.set_label("Foo", labelpad=-1)
```
Negative labelpad values will move closer to the bar, positive away.


Question:
Plot a histogram from a Dictionary I created a dictionary that counts the occurrences in a list of every key and I would now like to plot the histogram of its content. This is the content of the dictionary I want to plot:
```
{1: 27, 34: 1, 3: 72, 4: 62, 5: 33, 6: 36, 7: 20, 8: 12, 9: 9, 10: 6, 11: 5, 12: 8, 2: 74, 14: 4, 15: 3, 16: 1, 17: 1, 18: 1, 19: 1, 21: 1, 27: 2}
```
So far I wrote this:
```
import numpy as np
import matplotlib.pyplot as plt

pos = np.arange(len(myDictionary.keys()))
width = 1.0     # gives histogram aspect to the bar diagram

ax = plt.axes()
ax.set_xticks(pos + (width / 2))
ax.set_xticklabels(myDictionary.keys())

plt.bar(myDictionary.keys(), ******, width, color='g')
#                            ^^^^^^ what should I put here?
plt.show()
```
I tried by simply doing
```
plt.bar(myDictionary.keys(), myDictionary, width, color='g')
```
but this is the result: and I don't know why the 3 bars are shifted and also I'd like the histogram to be displayed in a ordered fashion. Can somebody tell me how to do it?

Response:
You can use the function for plotting histograms like this:
```
a = np.random.random_integers(0,10,20) #example list of values
plt.hist(a)
plt.show()
```
Or you can use myDictionary just like this:
```
plt.bar(myDictionary.keys(), myDictionary.values(), width, color='g')
```


Question:
savefig loop adds previous plots to figure I am trying to use a forloop to produce figures for each set of data I have, but while the .show() command produces the correct figure, .savefig() keeps adding the previous plotted values to the new figure. In my forloop, this is the relevant sample of the code.
```
import matplotlib.pyplot as plt
plt.plot(X,Y[:,0],'o-')
plt.xlabel('x')
plt.savefig('plot'+str(i)+'.png')
```
As a comparison, here is the savefig plot and here is that shown by show(). As can be seen, the savefig() plot also plotted the previous result.

Response: You have to close current figure after saving with function plt.close(): http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.close Or you have to clean current figure after saving by plt.clf(): http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.clf


Question:
How to change legend fontsize with matplotlib.pyplot Simple question here: I'm trying to get the size of my legend using matplotlib.pyplot to be smaller (i.e., the text to be smaller). The code I'm using goes something like this:
```
plot.figure()
plot.scatter(k, sum_cf, color='black', label='Sum of Cause Fractions')
plot.scatter(k, data[:, 0],  color='b', label='Dis 1: cf = .6, var = .2')
plot.scatter(k, data[:, 1],  color='r',  label='Dis 2: cf = .2, var = .1')
plot.scatter(k, data[:, 2],  color='g', label='Dis 3: cf = .1, var = .01')
plot.legend(loc=2)
```

Response:
You can set an individual font size for the legend by adjusting the prop keyword.
```
plot.legend(loc=2, prop={'size': 6})
```
This takes a dictionary of keywords corresponding to matplotlib.font_manager.FontProperties properties. See the documentation for legend: Keyword arguments:
```
prop: [ None | FontProperties | dict ]
    A matplotlib.font_manager.FontProperties instance. If prop is a
    dictionary, a new instance will be created with prop. If None, use
    rc settings.
```
It is also possible, as of version 1.2.1, to use the keyword fontsize.


Question:
Increasing the space for x axis labels in Matplotlib I'm plotting, but find that I need to increase the area underneath chart such that I can plot the labels vertically but in a font size that is not so tiny. At the moment, I have:
```
plt.figure(count_fig) fig, ax = plt.subplots()
rects1 = ax.bar(ind, ratio_lst, width, color='r', linewidth=1, alpha=0.8, log=1)
ax.set_ylabel('')
ax.set_title('')
ax.set_xticks(ind_width)
ax.set_xticklabels(labels_lst, rotation='vertical', fontsize=6)
```
At the moment it works, but the labels often run-off the edge of the plot.

Response:
subplots_adjust will do it. You can play with the bottom keyword to get a good placement of the bottom of the plot.
```
fig.subplots_adjust(bottom=0.2)
```


Question:
Creating multiple boxplots on the same graph from a dictionary I am trying to create a graph whereby the x axis is the key of the dictionary and the boxplot is from the information inside the dictionary. My dictionary can have many keys.
```py
Data = {'ABC': [34.54, 34.345, 34.761], 'DEF': [34.541, 34.748, 34.482]}

for ID in Data:
        plt.boxplot(Data[ID])
        plt.xlabel(ID)
plt.savefig('BoxPlot.png')
plt.clf()
```
It however seems to put the box plots on top of each other. I tried iterating the positions value within boxplot with no luck. I would also like to use the key as the xaxis value for each boxplot if possible.

Response:
```
my_dict = {'ABC': [34.54, 34.345, 34.761], 'DEF': [34.541, 34.748, 34.482]}

fig, ax = plt.subplots()
ax.boxplot(my_dict.values())
ax.set_xticklabels(my_dict.keys())
```


Question:
Named colors in matplotlib What named colors are available in matplotlib for use in plots? I can find a list on the matplotlib documentation that claims that these are the only names:
```
b: blue
g: green
r: red
c: cyan
m: magenta
y: yellow
k: black
w: white
```
However, I've found that these colors can also be used, at least in this context:
```
scatter(X,Y, color='red')
scatter(X,Y, color='orange')
scatter(X,Y, color='darkgreen')
```
but these are not on the above list. Does anyone know an exhaustive list of the named colors that are available?

Response:
I constantly forget the names of the colors I want to use and keep coming back to this question =) The previous answers are great, but I find it a bit difficult to get an overview of the available colors from the posted image. I prefer the colors to be grouped with similar colors, so I slightly tweaked the matplotlib answer that was mentioned in a comment above to get a color list sorted in columns. The order is not identical to how I would sort by eye, but I think it gives a good overview. I updated the image and code to reflect that 'rebeccapurple' has been added and the three sage colors have been moved under the 'xkcd:' prefix since I posted this answer originally. I really didn't change much from the matplotlib example, but here is the code for completeness.
```
import matplotlib.pyplot as plt
from matplotlib import colors as mcolors

colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)

# Sort colors by hue, saturation, value and name.
by_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgba(color)[:3])), name)
                for name, color in colors.items())
sorted_names = [name for hsv, name in by_hsv]

n = len(sorted_names)
ncols = 4
nrows = n // ncols

fig, ax = plt.subplots(figsize=(12, 10))

# Get height and width
X, Y = fig.get_dpi() * fig.get_size_inches()
h = Y / (nrows + 1)
w = X / ncols

for i, name in enumerate(sorted_names):
    row = i % nrows
    col = i // nrows
    y = Y - (row * h) - h

    xi_line = w * (col + 0.05)
    xf_line = w * (col + 0.25)
    xi_text = w * (col + 0.3)

    ax.text(xi_text, y, name, fontsize=(h * 0.8),
            horizontalalignment='left',
            verticalalignment='center')

    ax.hlines(y + h * 0.1, xi_line, xf_line,
              color=colors[name], linewidth=(h * 0.8))

ax.set_xlim(0, X)
ax.set_ylim(0, Y)
ax.set_axis_off()

fig.subplots_adjust(left=0, right=1,
                    top=1, bottom=0,
                    hspace=0, wspace=0)
plt.show()
```
Additional named colors Updated 2017-10-25. I merged my previous updates into this section. xkcd If you would like to use additional named colors when plotting with matplotlib, you can use the xkcd crowdsourced color names, via the 'xkcd:' prefix:
```
plt.plot([1,2], lw=4, c='xkcd:baby poop green')
```
Now you have access to a plethora of named colors! Tableau The default Tableau colors are available in matplotlib via the 'tab:' prefix:
```
plt.plot([1,2], lw=4, c='tab:green')
```
There are ten distinct colors: HTML You can also plot colors by their HTML hex code:
```
plt.plot([1,2], lw=4, c='#8f9805')
```
This is more similar to specifying and RGB tuple rather than a named color (apart from the fact that the hex code is passed as a string), and I will not include an image of the 16 million colors you can choose from... For more details, please refer to the matplotlib colors documentation and the source file specifying the available colors, _color_data.py.


Question:
Displaying Matplotlib Navigation Toolbar in Tkinter via grid I'm developing a small Tkinter GUI to draw matplotlib-plots. (It contains a few Entries and assembles the plot according to their content.) I have designed my plotting widget according to http://matplotlib.org/examples/user_interfaces/embedding_in_tk.html, only I use grid instead of pack:
```
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.get_tk_widget().grid(row=1,column=4,columnspan=3,rowspan=20)
```
That part works. But embedding the NavigationToolbar in the same fashion does not. Tkinter breaks down without error when I include the lines:
```
toolbar = NavigationToolbar2TkAgg( canvas, root )
canvas._tkcanvas.grid(row=22,column=4)
```
I know this is because NavigationToolbar calls pack internally, and pack and grid don't get along. However, I like grid and would hate to have to redesign my whole GUI just to be able to use the NavigationToolbar. Is there a workaround so I can use NavigationToolbar2TkAgg via grid? (I have found the advice to "subclass and overload" here, but don't know how to do that.) Any help greatly appreciated!

Response:
Here is a code example for what was mentioned in Bryan Oakleys answer (add toolbar to frame, place frame on grid):
```
fig = Figure(figsize=(5, 5), dpi=100)

    canvas = FigureCanvasTkAgg(fig, master=root)
    canvas.get_tk_widget().grid(row=1,column=4,columnspan=3,rowspan=20)
    # here: plot suff to your fig
    canvas.draw()

    ###############    TOOLBAR    ###############
    toolbarFrame = Frame(master=root)
    toolbarFrame.grid(row=22,column=4)
    toolbar = NavigationToolbar2TkAgg(canvas, toolbarFrame)
```


Question:
Python saving multiple figures into one PDF file In python (for one figure created in a GUI) I was able to save the figure under .jpg and also .pdf by either using:
```
plt.savefig(filename1 +  '.pdf')
```
or
```
plt.savefig(filename1 +  '.jpg')
```
Using one file I would like to save multiple figures in either .pdf or .jpg (just like its done in math lab). Can anybody please help with this?

Response:
Use PdfPages to solve your problem. Pass your figure object to the savefig method. For example, if you have a whole pile of figure objects open and you want to save them into a multi-page PDF, you might do:
```
import matplotlib.backends.backend_pdf
pdf = matplotlib.backends.backend_pdf.PdfPages("output.pdf")
for fig in xrange(1, figure().number): ## will open an empty extra figure :(
    pdf.savefig( fig )
pdf.close()
```


Question:
'invalid value encountered in double_scalars' warning, possibly numpy As I run my code I get these warnings, always in groups of four, sporadically. I have tried to locate the source by placing debug messages before and after certain statements to pin-point its origin.
```
Warning: invalid value encountered in double_scalars
Warning: invalid value encountered in double_scalars
Warning: invalid value encountered in double_scalars
Warning: invalid value encountered in double_scalars
```
Is this is a Numpy warning, and what is a double scalar? From Numpy I use
```
min(), argmin(), mean() and random.randn()
```
I also use Matplotlib

Response: It looks like a floating-point calculation error. Check the numpy.seterr function to get more information about where it happens.


Question:
Edit the width of bars using pd.DataFrame.plot() I am making a stacked bar plot using:
```
DataFrame.plot(kind='bar',stacked=True)
```
I want to control width of bars so that the bars are connected to each other like a histogram. I've looked through the documentation but to no avail - any suggestions? Is it possible to do it this way?

Response:
For anyone coming across this question: Since pandas 0.14, plotting with bars has a 'width' command: https://github.com/pydata/pandas/pull/6644 The example above can now be solved simply by using
```
df.plot(kind='bar', stacked=True, width=1)
```
See pandas.DataFrame.plot.bar or pandas.DataFrame.plot with kind='bar'. When changing the width of the bars, it might also be appropriate to change the figure size by specifying the figsize= parameter.


Question: How to change the color of the axis, ticks and labels I'd like to change the color of the axis, as well as ticks and value-labels for a plot I did using matplotlib and PyQt.

Response:
As a quick example (using a slightly cleaner method than the potentially duplicate question):
```
import matplotlib.pyplot as plt

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

ax.plot(range(10))
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')

ax.spines['bottom'].set_color('red')
ax.spines['top'].set_color('red')
ax.xaxis.label.set_color('red')
ax.tick_params(axis='x', colors='red')

plt.show()
```
Alternatively
```py
[t.set_color('red') for t in ax.xaxis.get_ticklines()]
[t.set_color('red') for t in ax.xaxis.get_ticklabels()]
```


Question: Plot negative values on a log scale I am doing some analysis to calculate the value of log_10(x) which is a negative number. I am now trying to plot these values, however, since the range of the answers is very large I would like to use a logarithmic scale for this. If I simply use plt.yscale('log') I get a message telling me UserWarning: Data has no positive values, and therefore cannot be log-scaled. I also cannot supply the values of x to plt.plot as the result of log_10(x) is so large and negative that the answer of x**(log_10(x)) is simply 0. What might be the most straightforward way of plotting this data?

Response:
You can use
```
plt.yscale('symlog')
```
to set the scale to a symmetic log scale. This means that it will scale logarithmically to both sides of 0. Only using the negative part of the symlog scale would work just fine.


Question:
How to set ticks on Fixed Position , matplotlib Can anyone help me set the ticks on a fixed position using matplotlib? I've tried using FixedPosition as this tutorial describes:
```
ax = pl.gca()
ax.xaxis.set_major_locator(eval(locator))
```
http://scipy-lectures.github.io/intro/matplotlib/matplotlib.html#figures-subplots-axes-and-ticks But when I try to run, it tells me that set_major_locator method does not exist. A simple example would be very useful. Thanks.

Response:
Just use ax.set_xticks(positions) or ax.set_yticks(positions). For example:
```
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.set_xticks([0.15, 0.68, 0.97])
ax.set_yticks([0.2, 0.55, 0.76])
plt.show()
```


Question: Create automated strictly-designed multi-page PDF report from HTML [closed] Closed. This question is seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. It does not meet Stack Overflow guidelines. It is not currently accepting answers. We don’t allow questions seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. You can edit the question so it can be answered with facts and citations. Closed 2 years ago. The community reviewed whether to reopen this question 2 years ago and left it closed: Original close reason(s) were not resolved Improve this question What are good Python-based options to create strictly designed PDF reports from HTML? I've attached a draft PDF to illustrate the following points: The design of the report is rather strictly designed. In other words "Looks matter". The report contains complex vector graphics (package: Matplotlib).These may slightly differ in size . The report contains images. The report contains a large number of numbers / strings filled in dynamically. Optimally, the solution would use open source packages. We create our HTML with Django. The report may span multiple pages. It looks as if there was already a good amount of very diverse packages facilitating reporting. Just to name a few, there are xhtml2pdf, weasyprint, django-wkhtmltopdf. In my experience, it’s easy with these tools to create a PDF from your content. The hard part comes when the PDF needs to fall into a highly-defined design structure as in our case. Unfortunately, I was not able to find example PDFs for the different PDF generation packages that have a highly designed structure. What is your experience with this? Which options worked well for you? Are there well done complex examples that I’ve overlooked?

Response: You can see this Python package: weasyprint Web page: http://weasyprint.org/ Official doc: http://weasyprint.readthedocs.io/en/latest/ It's great, because you can generate the PDF from a web page or an html file, you can have conflicts with some CSS (which are specified in the documentation), but it provides what you need


Question: Plotting a 2D heatmap Using Matplotlib, I want to plot a 2D heat map. My data is an n-by-n Numpy array, each with a value between 0 and 1. So for the (i, j) element of this array, I want to plot a square at the (i, j) coordinate in my heat map, whose color is proportional to the element's value in the array. How can I do this?

Response:
The imshow() function with parameters interpolation='nearest' and cmap='hot' should do what you want. Please review the interpolation parameter details, and see Interpolations for imshow and Image antialiasing.
```
import matplotlib.pyplot as plt
import numpy as np

a = np.random.random((16, 16))
plt.imshow(a, cmap='hot', interpolation='nearest')
plt.show()
```


Question: more than 9 subplots in matplotlib Is it possible to get more than 9 subplots in matplotlib? I am on the subplots command pylab.subplot(449); how can I get a 4410 to work? Thank you very much.

Response: It was easier than I expected, I just did: pylab.subplot(4,4,10) and it worked.


Question:
How do I plot only a table in Matplotlib? Is it possible to draw only a table with matplotlib? If I uncomment the line
```
plt.bar(index, data[row], bar_width, bottom=y_offset, color=colors[row])
```
of this example code, the plot is still visible. I want to have a table on top of my (PyQt) window and underneath a plot (with some space in between).

Response:
This is another option to write a pandas dataframe directly into a matplotlib table:
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

# hide axes
fig.patch.set_visible(False)
ax.axis('off')
ax.axis('tight')

df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD'))

ax.table(cellText=df.values, colLabels=df.columns, loc='center')

fig.tight_layout()

plt.show()
```


Question: Plot yerr/xerr as shaded region rather than error bars In matplotlib, how do I plot error as a shaded region rather than error bars? For example: rather than

Response:
Ignoring the smooth interpolation between points in your example graph (that would require doing some manual interpolation, or just have a higher resolution of your data), you can use pyplot.fill_between():
```
from matplotlib import pyplot as plt
import numpy as np

x = np.linspace(0, 30, 30)
y = np.sin(x/6*np.pi)
error = np.random.normal(0.1, 0.02, size=y.shape)
y += np.random.normal(0, 0.1, size=y.shape)

plt.plot(x, y, 'k-')
plt.fill_between(x, y-error, y+error)
plt.show()
```
See also the matplotlib examples.


Question:
How to change size of figure with subplots I'm having some trouble trying to change the figure size when using plt.subplots. With the following code, I just get the standard size graph with all my subplots bunched in (there's ~100) and obviously just an extra empty figuresize . I've tried using tight_layout, but to no avail.
```py
def plot(reader):
    channels=[]
    for i in reader:
        channels.append(i)

    plt.figure(figsize=(50,100))
    fig, ax = plt.subplots(len(channels), sharex=True)

    plot=0
    for j in reader:

        ax[plot].plot(reader["%s" % j])
        plot=plot+1

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

Response:
You can remove your initial plt.figure(). When calling plt.subplots() a new figure is created, so you first call doesn't do anything. The subplots command in the background will call plt.figure() for you, and any keywords will be passed along. So just add the figsize keyword to the subplots() command:
```
def plot(reader):
    channels=[]
    for i in reader:
        channels.append(i)

    fig, ax = plt.subplots(len(channels), sharex=True, figsize=(50,100))

    plot=0
    for j in reader:

        ax[plot].plot(reader["%s" % j])
        plot=plot+1

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


Question: Boxplots in matplotlib: Markers and outliers I have some questions about boxplots in matplotlib: Question A. What do the markers that I highlighted below with Q1, Q2, and Q3 represent? I believe Q1 is maximum and Q3 are outliers, but what is Q2? Question B How does matplotlib identify outliers? (i.e. how does it know that they are not the true max and min values?)

Response: A picture is worth a thousand words. Note that the outliers (the + markers in your plot) are simply points outside of the wide [(Q1-1.5 IQR), (Q3+1.5 IQR)] margin below. However, the picture is only an example for a normally distributed data set. It is important to understand that matplotlib does not estimate a normal distribution first and calculates the quartiles from the estimated distribution parameters as shown above. Instead, the median and the quartiles are calculated directly from the data. Thus, your boxplot may look different depending on the distribution of your data and the size of the sample, e.g., asymmetric and with more or less outliers.


Question:
Pandas and Matplotlib - fill_between() vs datetime64 There is a Pandas DataFrame:
```
<class 'pandas.core.frame.DataFrame'>
Int64Index: 300 entries, 5220 to 5519
Data columns (total 3 columns):
Date             300 non-null datetime64[ns]
A                300 non-null float64
B                300 non-null float64
dtypes: datetime64[ns](1), float64(2)
memory usage: 30.5 KB
```
I want to plot A and B series vs Date.
```
plt.plot_date(data['Date'], data['A'], '-')
plt.plot_date(data['Date'], data['B'], '-')
```
Then I want apply fill_between() on area between A and B series:
```
plt.fill_between(data['Date'], data['A'], data['B'],
                where=data['A'] >= data['B'],
                facecolor='green', alpha=0.2, interpolate=True)
```
Which outputs:
```
TypeError: ufunc 'isfinite' not supported for the input types, and the inputs
could not be safely coerced to any supported types according to the casting
rule ''safe''
```
Does matplotlib accept pandas datetime64 object in fill_between() function? Should I convert it to different date type?

Response:
Pandas registers a converter in matplotlib.units.registry which converts a number of datetime types (such as pandas DatetimeIndex, and numpy arrays of dtype datetime64) to matplotlib datenums, but it does not handle Pandas Series with dtype datetime64.
```

```python
import pandas.tseries.converter as converter
```

```python
c = converter.DatetimeConverter()
```

```python
type(c.convert(df['Date'].values, None, None))
#Output
#numpy.ndarray              # converted (good)
```

```python
type(c.convert(df['Date'], None, None))
#Output
#pandas.core.series.Series  # left unchanged
#```
#fill_between checks for and uses a converter to handle the data if it exists. So as a workaround, you could convert the dates to a NumPy array of datetime64's:
#```
#d = data['Date'].values
#plt.fill_between(d, data['A'], data['B'],
#                where=data['A'] >= data['B'],
#                facecolor='green', alpha=0.2, interpolate=True)
#```
#For example,
#```
#import numpy as np
#import matplotlib.pyplot as plt
#import pandas as pd
#
#N = 300
#dates = pd.date_range('2000-1-1', periods=N, freq='D')
#x = np.linspace(0, 2*np.pi, N)
#data = pd.DataFrame({'A': np.sin(x), 'B': np.cos(x),
#               'Date': dates})
#plt.plot_date(data['Date'], data['A'], '-')
#plt.plot_date(data['Date'], data['B'], '-')
#
#d = data['Date'].values
#plt.fill_between(d, data['A'], data['B'],
#                where=data['A'] >= data['B'],
#                facecolor='green', alpha=0.2, interpolate=True)
#plt.xticks(rotation=25)
#plt.show()
#```
```


Question:
plot pandas dataframe two columns i have a pandas dataframe which has dates as indexes and some columns: I would like to plot a line chart with 2 lines (let's say 'ISP.MI' and 'Ctrv'); on the x axis I need the 'Date'
```
Ticker       ISP.MI  Daily returns        Ctrv  Inv_Am  Giac_Media
Date
2016-01-01  2.90117            NaN  100.000000     100       100.0
2016-01-04  2.80159      -0.034927  196.507301     200       150.0
2016-01-05  2.85608       0.019263  300.292610     300       200.0
2016-01-06  2.77904      -0.027345  392.081255     400       250.0
2016-01-07  2.73206      -0.017050  485.396411     500       300.0
2016-01-08  2.72267      -0.003443  583.725246     600       350.0
```

Response:
I think the simpliest is select columns by subset and then DataFrame.plot:
```
df[['ISP.MI','Ctrv']].plot()
```


Question:
Plotting transparent histogram with non transparent edge I am plotting a histogram, and I have three datasets which I want to plot together, each one with different colours and linetype (dashed, dotted, etc). I am also giving some transparency, in order to see the overlapping bars. The point is that I would like the edge of each bar not to become transparent as the inner part does. Here is an example:
```
import matplotlib.pyplot as plt
import numpy as np

x = np.random.random(20)
y =np.random.random(20)
z= np.random.random(20)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.hist(x, bins=np.arange(0, 1, 0.1), ls='dashed', alpha = 0.5, lw=3, color= 'b')
ax.hist(y, bins=np.arange(0, 1, 0.1), ls='dotted', alpha = 0.5, lw=3, color= 'r')
ax.hist(z, bins=np.arange(0, 1, 0.1), alpha = 0.5, lw=3, color= 'k')
ax.set_xlim(-0.5, 1.5)
ax.set_ylim(0, 7)
plt.show()
```

Response:
plt.hist accepts additional keyword arguments that are passed to the constructor for matplotlib.patches.Patch. In particular you can pass an fc= argument which lets you set the patch facecolor using an (R, G, B, A) tuple when you create the histograms. Changing the alpha value of the facecolor does not affect the transparency of the edges:
```
ax.hist(x, bins=np.arange(0, 1, 0.1), ls='dashed', lw=3, fc=(0, 0, 1, 0.5))
ax.hist(y, bins=np.arange(0, 1, 0.1), ls='dotted', lw=3, fc=(1, 0, 0, 0.5))
ax.hist(z, bins=np.arange(0, 1, 0.1), lw=3, fc=(0, 0, 0, 0.5))
```


Question:
Inserting a degree symbol into python plot This is a really simple problem but its escaping me. I'm just trying to insert a degree symbol into the titles and legends of my python plot. Code is below. Thanks.
```
from numpy import *
import numpy as np
import matplotlib.pyplot as plt

theta1 = linspace(0,60,610)
theta2 = linspace(0,45,460)
theta3 = linspace(45,90,460)

CTS = 1/cos(radians(theta1))
CTS0 = 1/cos(radians(60-theta2))
CTS45 = 1/cos(radians(105-theta3))

plt.plot(theta1,CTS,label=u'CTS Head at 0',linewidth=2)
plt.plot(theta2,CTS0,label='CTS Head at 60',linewidth=2)
plt.plot(theta3,CTS45,label='CTS Head at 105',linewidth=2)

plt.xlabel('Manufactured Ply Angle (degrees)')
plt.ylabel('Thickness')

plt.legend( loc='lower right', numpoints = 1 )
plt.ylim([0,2.5])

plt.grid(b=None, which='major', axis='both')
plt.grid(color='k', linestyle='--', linewidth=0.5)
plt.axhline(y=1.035, xmin=0, xmax=90,color='k', linestyle='-', linewidth=1)

plt.show()
```

Response: Use LaTeX Style. For Example: $^\circ$ Text would produce °Text See the matplotlib documentation for more information about printing (especially mathematical expression). In your case the code has to be: plt.xlabel('Manufactured Ply Angle $^\circ$') The TeX part of the expression must be enclosed by dollar signs "$".


Question:
How can I plot NaN values as a special color with imshow? I am trying to use imshow in matplotlib to plot data as a heatmap, but some of the values are NaNs. I'd like the NaNs to be rendered as a special color not found in the colormap. example:
```
import numpy as np
import matplotlib.pyplot as plt
f = plt.figure()
ax = f.add_subplot(111)
a = np.arange(25).reshape((5,5)).astype(float)
a[3,:] = np.nan
ax.imshow(a, interpolation='nearest')
f.canvas.draw()
```
The resultant image is unexpectedly all blue (the lowest color in the jet colormap). However, if I do the plotting like this:
```
ax.imshow(a, interpolation='nearest', vmin=0, vmax=24)
```
--then I get something better, but the NaN values are drawn the same color as vmin... Is there a graceful way that I can set NaNs to be drawn with a special color (eg: gray or transparent)?

Response:
With newer versions of Matplotlib, it is not necessary to use a masked array anymore. For example, let’s generate an array where every 7th value is a NaN:
```
arr = np.arange(100, dtype=float).reshape(10, 10)
arr[~(arr % 7).astype(bool)] = np.nan
```
.cm.get_cmap() is replaced by .colormaps.get_cmap('viridis') in matplotlib v3.7.0 Set the color with .set_bad.
```py
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

arr = np.arange(100, dtype=float).reshape(10, 10)
arr[~(arr % 7).astype(bool)] = np.nan

cmap = mpl.colormaps.get_cmap('viridis')  # viridis is the default colormap for imshow
cmap.set_bad(color='red')

plt.imshow(arr, cmap=cmap)
```
.cm.get_cmap() is deprecated We can modify the current colormap and plot the array with the following lines:
```
current_cmap = mpl.cm.get_cmap()
current_cmap.set_bad(color='red')
plt.imshow(arr)
```


Question:
ValueError: x and y must be the same size
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as pt

data1 = pd.read_csv('stage1_labels.csv')

X = data1.iloc[:, :-1].values
y = data1.iloc[:, 1].values

from sklearn.preprocessing import LabelEncoder, OneHotEncoder
label_X = LabelEncoder()
X[:,0] = label_X.fit_transform(X[:,0])
encoder = OneHotEncoder(categorical_features = [0])
X = encoder.fit_transform(X).toarray()

from sklearn.cross_validation import train_test_split
X_train, X_test, y_train,y_test = train_test_split(X, y, test_size = 0.4, random_state = 0)

#fitting Simple Regression to training set

from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)

#predecting the test set results
y_pred = regressor.predict(X_test)

#Visualization of the training set results
pt.scatter(X_train, y_train, color = 'red')
pt.plot(X_train, regressor.predict(X_train), color = 'green')
pt.title('salary vs yearExp (Training set)')
pt.xlabel('years of experience')
pt.ylabel('salary')
pt.show()
```
I need a help understanding the error in while executing the above code. Below is the error: "raise ValueError("x and y must be the same size")" I have .csv file with 1398 rows and 2 column. I have taken 40% as y_test set, as it is visible in the above code.

Response: Print X_train shape. What do you see? I'd bet X_train is 2d (matrix with a single column), while y_train 1d (vector). In turn you get different sizes. I think using X_train[:,0] for plotting (which is from where the error originates) should solve the problem


Question: Python - Plotting colored grid based on values I have been searching here and on the net. I found somehow close questions/answers to what I want, but still couldn't reach to what I'm looking for. I have an array of for example, 100 values. The values are in the range from 0 to 100. I want to plot this array as a grid, filling the squares according to the values in the array. The solutions I found so far are like the followings: Drawing grid pattern in matplotlib and custom matplotlib plot : chess board like table with colored cells In the examples I mentioned, the ranges of the colors vary and are not fixed. However, what I am wondering about, is whether I can set the ranges for specific values and colors. For example, if the values are between 10 and 20, let the color of the grid square be red. else if the values are between 20 and 30, let the color be blue. etc. How this could be achieved in python?

Response:
You can create a ListedColormap for your custom colors and color BoundaryNorms to threshold the values.
```
import matplotlib.pyplot as plt
from matplotlib import colors
import numpy as np

data = np.random.rand(10, 10) * 20

# create discrete colormap
cmap = colors.ListedColormap(['red', 'blue'])
bounds = [0,10,20]
norm = colors.BoundaryNorm(bounds, cmap.N)

fig, ax = plt.subplots()
ax.imshow(data, cmap=cmap, norm=norm)

# draw gridlines
ax.grid(which='major', axis='both', linestyle='-', color='k', linewidth=2)
ax.set_xticks(np.arange(-.5, 10, 1));
ax.set_yticks(np.arange(-.5, 10, 1));

plt.show()
```
Resulting in; For more, you can check this matplotlib example.


Question:
What is y axis in seaborn distplot? I have some geometrically distributed data. When I want to take a look at it, I use
```
sns.distplot(data, kde=False, norm_hist=True, bins=100)
```
which results is a picture: However, bins heights don't add up to 1, which means y axis doesn't show probability, it's something different. If instead we use
```
weights = np.ones_like(np.array(data))/float(len(np.array(data)))
plt.hist(data, weights=weights, bins = 100)
```
the y axis shall show probability, as bins heights sum up to 1: It can be seen more clearly here: suppose we have a list
```
l = [1, 3, 2, 1, 3]
```
We have two 1s, two 3s and one 2, so their respective probabilities are 2/5, 2/5 and 1/5. When we use seaborn histplot with 3 bins:
```
sns.distplot(l, kde=False, norm_hist=True, bins=3)
```
we get: As you can see, the 1st and the 3rd bin sum up to 0.6+0.6=1.2 which is already greater than 1, so y axis is not a probability. When we use
```
weights = np.ones_like(np.array(l))/float(len(np.array(l)))
plt.hist(l, weights=weights, bins = 3)
```
we get: and the y axis is probability, as 0.4+0.4+0.2=1 as expected. The amount of bins in these 2 cases are is the same for both methods used in each case: 100 bins for geometrically distributed data, 3 bins for small array l with 3 possible values. So bins amount is not the issue. My question is: in seaborn distplot called with norm_hist=True, what is the meaning of y axis?

Response: The x-axis is the value of the variable just like in a histogram, but what exactly does the y-axis represent? ANS-> The y-axis in a density plot is the probability density function for the kernel density estimation. However, we need to be careful to specify this is a probability density and not a probability. The difference is the probability density is the probability per unit on the x-axis. To convert to an actual probability, we need to find the area under the curve for a specific interval on the x-axis. Somewhat confusingly, because this is a probability density and not a probability, the y-axis can take values greater than one. The only requirement of the density plot is that the total area under the curve integrates to one. I generally tend to think of the y-axis on a density plot as a value only for relative comparisons between different categories. from the reference of https://towardsdatascience.com/histograms-and-density-plots-in-python-f6bda88f5ac0


Question: Matplotlib log scale tick label number formatting With matplotlib when a log scale is specified for an axis, the default method of labeling that axis is with numbers that are 10 to a power eg. 10^6. Is there an easy way to change all of these labels to be their full numerical representation? eg. 1, 10, 100, etc. Note that I do not know what the range of powers will be and want to support an arbitrary range (negatives included).

Response:
Sure, just change the formatter. For example, if we have this plot:
```
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.axis([1, 10000, 1, 100000])
ax.loglog()

plt.show()
```
You could set the tick labels manually, but then the tick locations and labels would be fixed when you zoom/pan/etc. Therefore, it's best to change the formatter. By default, a logarithmic scale uses a LogFormatter, which will format the values in scientific notation. To change the formatter to the default for linear axes (ScalarFormatter) use e.g.
```
from matplotlib.ticker import ScalarFormatter
for axis in [ax.xaxis, ax.yaxis]:
    axis.set_major_formatter(ScalarFormatter())
```