Question:
Plotting a horizontal line on multiple subplots in python using pyplot I am plotting three subplots on the same page. I want to draw a horiZontal line through all the subplots. Following is my code and the resultant graph: (You can notice I can get the horizontal line on one of the plots, but not all)
```
gs1 = gridspec.GridSpec(8, 2)
gs1.update(left=0.12, right=.94, wspace=0.12)
ax1 = plt.subplot(gs1[0:2, :])
ax2 = plt.subplot(gs1[3:5, :], sharey=ax1)
ax3 = plt.subplot(gs1[6:8, :], sharey=ax1)

ax1.scatter(theta_cord, density, c = 'r', marker= '1')
ax2.scatter(phi_cord, density, c = 'r', marker= '1')
ax3.scatter(r_cord, density, c = 'r', marker= '1')
ax1.set_xlabel('Theta (radians)')
ax1.set_ylabel('Galaxy count')
ax2.set_xlabel('Phi (radians)')
ax2.set_ylabel('Galaxy count')
ax3.set_xlabel('Distance (Mpc)')
ax3.set_ylabel('Galaxy count')
plt.ylim((0,0.004))
loc = plticker.MultipleLocator(base=0.001)
ax1.yaxis.set_major_locator(loc)

plt.axhline(y=0.002, xmin=0, xmax=1, hold=None)

plt.show()
```
This generates the following: Again, I want the line I drew on the last subplot to appear on the first two subplots too. How do I do that?

Response:
I found a way to do it for anyone who stumbles on this anyways. We need to replace the following line from the OP:
```
plt.axhline(y=0.002, xmin=0, xmax=1, hold=None)
```
We replace it with:
```
ax1.axhline(y=0.002,xmin=0,xmax=3,c="blue",linewidth=0.5,zorder=0)
ax2.axhline(y=0.002,xmin=0,xmax=3,c="blue",linewidth=0.5,zorder=0)
ax3.axhline(y=0.002,xmin=0,xmax=3,c="blue",linewidth=0.5,zorder=0)
```
This produces:


Question:
How to have logarithmic bins in a Python histogram As far as I know the option Log=True in the histogram function only refers to the y-axis.
```
P.hist(d,bins=50,log=True,alpha=0.5,color='b',histtype='step')
```
I need the bins to be equally spaced in log10. Is there something that can do this?

Response:
use logspace() to create a geometric sequence, and pass it to bins parameter. And set the scale of xaxis to log scale.
```
import pylab as pl
import numpy as np

data = np.random.normal(size=10000)
pl.hist(data, bins=np.logspace(np.log10(0.1),np.log10(1.0), 50))
pl.gca().set_xscale("log")
pl.show()
```


Question:
How to avoid overlapping of labels & autopct in a pie chart My Python code is:
```
values = [234, 64, 54,10, 0, 1, 0, 9, 2, 1, 7, 7]
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
          'Jul','Aug','Sep','Oct', 'Nov','Dec']

colors = ['yellowgreen', 'red', 'gold', 'lightskyblue',
          'white','lightcoral','blue','pink', 'darkgreen',
          'yellow','grey','violet','magenta','cyan']

plt.pie(values, labels=labels, autopct='%1.1f%%', shadow=True,
        colors=colors, startangle=90, radius=1.2)

plt.show()
```
Is it possible to show the labels "Jan", "Feb", "Mar", etc. and the percentages, either: without overlapping, or using an arrow mark?

Response:
Alternatively you can put the legends beside the pie graph:
```
import matplotlib.pyplot as plt
import numpy as np

x = np.char.array(['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct', 'Nov','Dec'])
y = np.array([234, 64, 54,10, 0, 1, 0, 9, 2, 1, 7, 7])
colors = ['yellowgreen','red','gold','lightskyblue','white','lightcoral','blue','pink', 'darkgreen','yellow','grey','violet','magenta','cyan']
porcent = 100.*y/y.sum()

patches, texts = plt.pie(y, colors=colors, startangle=90, radius=1.2)
labels = ['{0} - {1:1.2f} %'.format(i,j) for i,j in zip(x, porcent)]

sort_legend = True
if sort_legend:
    patches, labels, dummy =  zip(*sorted(zip(patches, labels, y),
                                          key=lambda x: x[2],
                                          reverse=True))

plt.legend(patches, labels, loc='left center', bbox_to_anchor=(-0.1, 1.),
           fontsize=8)

plt.savefig('piechart.png', bbox_inches='tight')
```
EDIT: if you want to keep the legend in the original order, as you mentioned in the comments, you can set sort_legend=False in the code above, giving:


Question: How to hide ticks label in python but keep the ticks in place? I want to hide my ticks label on a plot I created, but keep this tick itself (the little marks on the axis). When I try to use what I've found here, for example, the entire tick is removed, and not just the labels. How can I remove only the labels then?

Response:
Here is a slightly simpler answer, using ax.tick_params
```
import matplotlib.pylab as plt

fig, ax = plt.subplots()
plt.plot([1,2,3],[4,5,6])

ax.tick_params(labelbottom=False)

plt.show()
```
Here is the resulting output in Matplotlib 3 As commented by @chris, one can similarly hide the labels on any of the other axes using labeltop, labelleft, labelright, in the above example, instead of labelbottom.


Question:
Annotate Time Series plot I have an index array (x) of dates (datetime objects) and an array of actual values (y: bond prices). Doing the following:
```py
plot(x,y)
```
produces a perfectly fine time series graph with the x-axis labeled with the dates. No problem so far. But I want to add text on certain dates. For example, on 2009-10-31, I wish to display the text "Event 1" with an arrow pointing to the y value at that date. I have read through the Matplotlib documentation on text() and annotate() to no avail.

Response:
Matplotlib uses an internal floating point format for dates. You just need to convert your date to that format (using matplotlib.dates.date2num or matplotlib.dates.datestr2num) and then use annotate as usual. As a somewhat excessively fancy example:
```
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

x = [dt.datetime(2009, 05, 01), dt.datetime(2010, 06, 01),
     dt.datetime(2011, 04, 01), dt.datetime(2012, 06, 01)]
y = [1, 3, 2, 5]

fig, ax = plt.subplots()
ax.plot_date(x, y, linestyle='--')

ax.annotate('Test', (mdates.date2num(x[1]), y[1]), xytext=(15, 15),
            textcoords='offset points', arrowprops=dict(arrowstyle='-|>'))

fig.autofmt_xdate()
plt.show()
```


Question:
Drawing lines between two plots in Matplotlib I am drawing two subplots with Matplotlib, essentially following :
```
subplot(211); imshow(a); scatter(..., ...)
subplot(212); imshow(b); scatter(..., ...)
```
Can I draw lines between those two subplots? How would I do that?

Response:
The solution from the other answers are suboptimal in many cases (as they would only work if no changes are made to the plot after calculating the points). A better solution would use the specially designed ConnectionPatch:
```
import matplotlib.pyplot as plt
from matplotlib.patches import ConnectionPatch
import numpy as np

fig = plt.figure(figsize=(10,5))
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)

x,y = np.random.rand(100),np.random.rand(100)

ax1.plot(x,y,'ko')
ax2.plot(x,y,'ko')

i = 10
xy = (x[i],y[i])
con = ConnectionPatch(xyA=xy, xyB=xy, coordsA="data", coordsB="data",
                      axesA=ax2, axesB=ax1, color="red")
ax2.add_artist(con)

ax1.plot(x[i],y[i],'ro',markersize=10)
ax2.plot(x[i],y[i],'ro',markersize=10)

plt.show()
```


Question:
set matplotlib 3d plot aspect ratio
```
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
```
Setting the aspect ratio works for 2d plots:
```
ax = plt.axes()
ax.plot([0,1], [0,10])
ax.set_aspect('equal', 'box')
```
But it does not work for 3d:
```
ax = plt.axes(projection='3d')
ax.plot([0,1], [0,1], [0,10])
ax.set_aspect('equal', 'box')
```
How do I set the aspect ratio for 3d?

Response:
As of matplotlib 3.3.0, Axes3D.set_box_aspect seems to be the recommended approach.
```py
import numpy as np
import matplotlib.pyplot as plt

xs, ys, zs = ...
ax = plt.axes(projection='3d')

ax.set_box_aspect((np.ptp(xs), np.ptp(ys), np.ptp(zs)))  # aspect ratio is 1:1:1 in data space

ax.plot(xs, ys, zs)
```


Question:
How to set x axis ticklabels in a seaborn plot [duplicate] This question already has answers here: Modify tick label text (13 answers) Closed 2 years ago. I am unable to set x axis ticklabels for a seaborn lineplot correctly.
```
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.DataFrame({'a':np.random.rand(8),'b':np.random.rand(8)})
sns.set(style="darkgrid")
g = sns.lineplot(data=df)
g.set_xticklabels(['2011','2012','2013','2014','2015','2016','2017','2018'])
```
The years on the x axis are not aligning properly.

Response:
Whenever you set the x-ticklabels manually, you should try to first set the corresponding ticks, and then specify the labels. In your case, therefore you should do
```
g = sns.lineplot(data=df)
g.set_xticks(range(len(df))) # <--- set the ticks first
g.set_xticklabels(['2011','2012','2013','2014','2015','2016','2017','2018'])
```


Question: How to extract data from matplotlib plot I have a wxPython program which reads from different datasets, performs various types of simple on-the-fly analysis on the data and plots various combinations of the datasets to matplotlib canvas. I would like to have the opportunity to dump currently plotted data to file for more sophisticated analysis later on. The question is: are there any methods in matplotlib that allow access to the data currently plotted in matplotlib.Figure?

Response:
Jakub is right about modifying the Python script to write out the data directly from the source from which it was sent into the plot; that's the way I'd prefer to do this. But for reference, if you do need to get data out of a plot, I think this should do it
```
gca().get_lines()[n].get_xydata()
```
Alternatively you can get the x and y data sets separately:
```
line = gca().get_lines()[n]
xd = line.get_xdata()
yd = line.get_ydata()
```


Question:
Using a Pandas dataframe index as values for x-axis in matplotlib plot I have time series in a Pandas dateframe with a number of columns which I'd like to plot. Is there a way to set the x-axis to always use the index from a dateframe? When I use the .plot() method from Pandas the x-axis is formatted correctly however I when I pass my dates and the column(s) I'd like to plot directly to matplotlib the graph doesn't plot correctly. Thanks in advance.
```
plt.plot(site2.index.values, site2['Cl'])
plt.show()
```
FYI: site2.index.values produces this (I've cut out the middle part for brevity):
```
array([
    '1987-07-25T12:30:00.000000000+0200',
    '1987-07-25T16:30:00.000000000+0200',
    '2010-08-13T02:00:00.000000000+0200',
    '2010-08-31T02:00:00.000000000+0200',
    '2010-09-15T02:00:00.000000000+0200'
],
dtype='datetime64[ns]')
```

Response:
You can use plt.xticks to set the x-axis try:
```
plt.xticks( site2['Cl'], site2.index.values ) # location, labels
plt.plot( site2['Cl'] )
plt.show()
```
see the documentation for more details: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.xticks


Question:
Plot Pandas DataFrame as Bar and Line on the same one chart I am trying to plot a chart with the 1st and 2nd columns of data as bars and then a line overlay for the 3rd column of data. I have tried the following code but this creates 2 separate charts but I would like this all on one chart.
```py
left_2013 = pd.DataFrame({'month': ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'],
                     '2013_val': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 6]})

right_2014 = pd.DataFrame({'month': ['jan', 'feb'], '2014_val': [4, 5]})

right_2014_target = pd.DataFrame({'month': ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'],
                                   '2014_target_val': [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]})

df_13_14 = pd.merge(left_2013, right_2014, how='outer')
df_13_14_target = pd.merge(df_13_14, right_2014_target, how='outer')
df_13_14_target[['month','2013_val','2014_val','2014_target_val']].head(12)

plt.figure()
df_13_14_target[['month','2014_target_val']].plot(x='month',linestyle='-', marker='o')
df_13_14_target[['month','2013_val','2014_val']].plot(x='month', kind='bar')
```
This is what I currently get

Response:
The DataFrame plotting methods return a matplotlib AxesSubplot or list of AxesSubplots. (See the docs for plot, or boxplot, for instance.) You can then pass that same Axes to the next plotting method (using ax=ax) to draw on the same axes:
```
ax = df_13_14_target[['month','2014_target_val']].plot(x='month',linestyle='-', marker='o')
df_13_14_target[['month','2013_val','2014_val']].plot(x='month', kind='bar',
   ax=ax)
```
```
import pandas as pd
import matplotlib.pyplot as plt

left_2013 = pd.DataFrame(
    {'month': ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep',
               'oct', 'nov', 'dec'],
     '2013_val': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 6]})

right_2014 = pd.DataFrame({'month': ['jan', 'feb'], '2014_val': [4, 5]})

right_2014_target = pd.DataFrame(
    {'month': ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep',
               'oct', 'nov', 'dec'],
     '2014_target_val': [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]})

df_13_14 = pd.merge(left_2013, right_2014, how='outer')
df_13_14_target = pd.merge(df_13_14, right_2014_target, how='outer')

ax = df_13_14_target[['month', '2014_target_val']].plot(
    x='month', linestyle='-', marker='o')
df_13_14_target[['month', '2013_val', '2014_val']].plot(x='month', kind='bar',
                                                        ax=ax)

plt.show()
```


Question:
Adding an axes using the same arguments as a previous axes I want to plot data, in two different subplots. After plotting, I want to go back to the first subplot and plot an additional dataset in it. However, when I do so I get this warning: MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance. warnings.warn(message, mplDeprecation, stacklevel=1) I can reproduce that with a simple piece of code:
```
import matplotlib.pyplot as plt
import numpy as np

# Generate random data
data = np.random.rand(100)

# Plot in different subplots
plt.figure()
plt.subplot(1, 2, 1)
plt.plot(data)

plt.subplot(1, 2, 2)
plt.plot(data)

plt.subplot(1, 2, 1) # Warning occurs here
plt.plot(data + 1)
```
Any ideas on how to avoid this warning? I use matplotlib 2.1.0. Looks like the same problem as here

Response:
This is a good example that shows the benefit of using matplotlib's object oriented API.
```
import numpy as np
import matplotlib.pyplot as plt

# Generate random data
data = np.random.rand(100)

# Plot in different subplots
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.plot(data)

ax2.plot(data)

ax1.plot(data+1)

plt.show()
```
Note: it is more pythonic to have variable names start with a lower case letter e.g. data = ... rather than Data = ... see PEP8


Question:
Extract matplotlib colormap in hex-format I am trying to extract discrete colors from a matplotlib colormap by manipulating this example. However, I cannot find the N discrete colors that are extracted from the colormap. In the code below I've used cmap._segmentdata, but I've found that it is the definition of the entire colormap. Given a colormap and an integer N, how do I extract N discrete colors from the colormap and export them in hex-format?
```
from pylab import *

delta = 0.01
x = arange(-3.0, 3.0, delta)
y = arange(-3.0, 3.0, delta)
X,Y = meshgrid(x, y)
Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = Z2 - Z1 # difference of Gaussians

cmap = cm.get_cmap('seismic', 5)    # PiYG
cmap_colors = cmap._segmentdata

def print_hex(r,b,g):
               if not(0 <= r <= 255 or 0 <= b <= 255 or 0 <= g <= 255):
                              raise ValueError('rgb not in range(256)')
               print '#%02x%02x%02x' % (r, b, g)

for i in range(len(cmap_colors['blue'])):
               r = int(cmap_colors['red'][i][2]*255)
               b = int(cmap_colors['blue'][i][2]*255)
               g = int(cmap_colors['green'][i][2]*255)
               print_hex(r, g, b)

im = imshow(Z, cmap=cmap, interpolation='bilinear',
            vmax=abs(Z).max(), vmin=-abs(Z).max())
axis('off')
colorbar()

show()
```

Response:
You can get a tuple of rgba values for the segment with index i by calling cmap(i). There is also already a function that turns rgb values into hex. As Joe Kington wrote in the comments, you can use matplotlib.colors.rgb2hex. Therefore, a possible solution would be:
```
from pylab import *

cmap = cm.get_cmap('seismic', 5)    # PiYG

for i in range(cmap.N):
    rgba = cmap(i)
    # rgb2hex accepts rgb or rgba
    print(matplotlib.colors.rgb2hex(rgba))
```
The output is:
```none
#00004c
#0000ff
#ffffff
#ff0000
#7f0000
```


Question:
How to add a title to each subplot I have one figure which contains many subplots.
```
fig = plt.figure(num=None, figsize=(26, 12), dpi=80, facecolor='w', edgecolor='k')
fig.canvas.set_window_title('Window Title')

# Returns the Axes instance
ax = fig.add_subplot(311)
ax2 = fig.add_subplot(312)
ax3 = fig.add_subplot(313)
```
How do I add titles to the subplots? fig.suptitle adds a title to all graphs and although ax.set_title() exists, the latter does not add any title to my subplots. Thank you for your help. Edit: Corrected typo about set_title(). Thanks Rutger Kassies

Response:
ax.title.set_text('My Plot Title') seems to work too.
```
fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
ax1.title.set_text('First Plot')
ax2.title.set_text('Second Plot')
ax3.title.set_text('Third Plot')
ax4.title.set_text('Fourth Plot')
plt.show()
```


Question:
How to set the labels size on a pie chart I want to have labels with small size on a piechart in python to improve visibility here is the code
```
import matplotlib.pyplot as plt

frac=[1.40 , 10.86 , 19.31 , 4.02 , 1.43 , 2.66 , 4.70 , 0.70 , 0.13 , 1.48, 32.96 , 1.11 , 13.30 , 5.86]
labels=['HO0900344', 'HO0900331', 'HO0900332', 'HO0900354',
'HO0900358', 'HO0900374', 'HO0900372', 'HO0900373',
'HO0900371', 'HO0900370', 'HO0900369', 'HO0900356',
'HO0900353', 'HO0900343']

fig = plt.figure(1, figsize=(6,6))
ax = fig.add_subplot(111)
ax.axis('equal')
colors=('b', 'g', 'r', 'c', 'm', 'y', 'burlywood', 'w')
ax.pie(frac,colors=colors ,labels=labels, autopct='%1.1f%%')
plt.show()
```

Response:
The simplest way to change the font size on a pie chart is directly via the textprops argument in the pie() function. Using the code above add it like so:
```
ax.pie(frac, colors=colors ,labels=labels,
       autopct='%1.1f%%', textprops={'fontsize': 14})
```
That way you can just pass in a dictionary with your desired fontsize (e.g., 14). No messing around with rcParams or return values from the function call.


Question:
Change y range to start from 0 with matplotlib I am using matplotlib to plot data. Here's a code that does something similar:
```
import matplotlib.pyplot as plt
f, ax = plt.subplots(1)
xdata = [1, 4, 8]
ydata = [10, 20, 30]
ax.plot(xdata, ydata)
plt.show(f)
```
This shows a line in a graph with the y axis that goes from 10 to 30. While I am satisfied with the x range, I would like to change the y range to start from 0 and adjust on the ymax to show everything. My current solution is to do:
```
ax.set_ylim(0, max(ydata))
```
However I am wondering if there is a way to just say: autoscale but starts from 0.

Response:
The range must be set after the plot.
```
import matplotlib.pyplot as plt
f, ax = plt.subplots(1)
xdata = [1, 4, 8]
ydata = [10, 20, 30]
ax.plot(xdata, ydata)
ax.set_ylim(ymin=0)
plt.show(f)
```
If ymin is changed before plotting, this will result in a range of [0, 1]. Edit: the ymin argument has been replaced by bottom:
```
ax.set_ylim(bottom=0)
```
Documentation: https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.set_ylim.html You can do the same on the x axis with left and right:
```
ax.set_xlim(left=0)
```
Documentation: https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.set_xlim.html


Question: Get default line color cycle I noticed when you plot that the first line is blue, then orange, then green, and so on. Is there some way to access this list of colors? I've seen a million posts on how to change the color cycle or access the iterator, but not on how to just get the list of colors that matplotlib cycles through by default.

Response:
Often, there is no need to get the default color cycle from anywhere, as it is the default one, so just using it is sufficient.
```
import numpy as np
import matplotlib.pyplot as plt

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

t = np.arange(5)

for i in range(4):
    line, = ax.plot(t,i*(t+1), linestyle = '-')
    ax.plot(t,i*(t+1)+.3,color = line.get_color(), linestyle = ':')

plt.show()
```
In case you want to use the default color cycle for something different, there are of course several options. "tab10" colormap First it should be mentionned that the "tab10" colormap comprises the colors from the default color cycle, you can get it via cmap = plt.get_cmap("tab10"). Equivalent to the above would hence be
```
import numpy as np
import matplotlib.pyplot as plt

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

t = np.arange(5)
cmap = plt.get_cmap("tab10")
for i in range(4):
    ax.plot(t,i*(t+1),   color=cmap(i), linestyle = '-')
    ax.plot(t,i*(t+1)+.3,color=cmap(i), linestyle = ':')

plt.show()
```
Colors from color cycle You can also use the color cycler directly, cycle = plt.rcParams['axes.prop_cycle'].by_key()['color']. This gives list with the colors from the cycle, which you can use to iterate over.
```
import numpy as np
import matplotlib.pyplot as plt

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

t = np.arange(5)
cycle = plt.rcParams['axes.prop_cycle'].by_key()['color']

for i in range(4):
    ax.plot(t,i*(t+1),   color=cycle[i], linestyle = '-')
    ax.plot(t,i*(t+1)+.3,color=cycle[i], linestyle = ':')

plt.show()
```
The CN notation Finally, the CN notation allows to get the Nth color of the color cycle, color="C{}".format(i). This however only works for the first 10 colors (N in [0,1,...9])
```
import numpy as np
import matplotlib.pyplot as plt

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

t = np.arange(5)

for i in range(4):
    ax.plot(t,i*(t+1),   color="C{}".format(i), linestyle = '-')
    ax.plot(t,i*(t+1)+.3,color="C{}".format(i), linestyle = ':')

plt.show()
```
All codes presented here produce the same plot.


Question: How to change the text color of font in legend? Is there a way to change the font color of the legend in a matplotlib plot? Specially in occasions where the background of the plot is dark, the default black text in the legend is hard or impossible to read.

Response:
As of matplotlib version 3.3.0, you can now directly use the keyword argument labelcolor in matplotlib.pyplot.legend(). Example using the same color as the corresponding artist by setting labelcolor='linecolor':
```py
import matplotlib.pyplot as plt
import numpy as np

plt.figure(figsize=(4, 3))
plt.plot(np.arange(10), np.random.rand(10) * 0, '-', label='spam')
plt.plot(np.arange(10), np.random.rand(10) * 1, ':', label='ham')
plt.plot(np.arange(10), np.random.rand(10) * 2, 'o', label='eggs')
plt.legend(labelcolor='linecolor')
```
Example changing all text to white by setting labelcolor='w', e.g. for dark backgrounds:
```py
import matplotlib.pyplot as plt
import numpy as np

plt.figure(figsize=(4, 3))
plt.plot(np.arange(10), np.random.rand(10) * 0, '-', label='spam')
plt.plot(np.arange(10), np.random.rand(10) * 1, ':', label='ham')
plt.plot(np.arange(10), np.random.rand(10) * 2, 'o', label='eggs')
plt.legend(facecolor='k', labelcolor='w')
```


Question:
How do I increase the line thickness for sns.lineplot? I have a few seaborn lineplots and I can't figure out how to increase the width of my lines. Here is my code
```
#graph 1
sns.lineplot(x="date", y="nps", data=df_nps, ax=ax1, label="NPS", color='#0550D0')
sns.lineplot(x="date", y="ema28", data=df_nps, ax=ax1, label="EMA28", color='#7DF8F3')
sns.lineplot(x="date", y="ema7", data=df_nps, ax=ax1, label="EMA7", color='orange')

#graph 2
dfz_nps_lineplot = sns.lineplot(x="date", y="nps", data=dfz_nps, ax=ax2, label="NPS", color='#0550D0')
dfz_nps_lineplot = sns.lineplot(x="date", y="ema28", data=dfz_nps, ax=ax2, label="EMA28", color='#7DF8F3')
dfz_nps_lineplot = sns.lineplot(x="date", y="ema7", data=dfz_nps, ax=ax2, label="EMA7", color='orange')

#graph3
dfp_nps_lineplot = sns.lineplot(x="date", y="nps", data=dfp_nps, ax=ax3, label="NPS", color='#0550D0')
dfp_nps_lineplot = sns.lineplot(x="date", y="ema28", data=dfp_nps, ax=ax3, label="EMA28", color='#7DF8F3')
dfp_nps_lineplot = sns.lineplot(x="date", y="ema7", data=dfp_nps, ax=ax3, label="EMA7", color='orange')

# formatting

plt.show()
```

Response: As you can see from seaborn.lineplot documentation, the function accepts matplotlib.axes.Axes.plot() arguments, which means you can pass the same arguments you can to matplotlib function in this documentation. If you want to simply adjust the width of your lineplots I find this the easiest: pass an argument linewidth = your_desired_line_width_in_float , for example, linewidth = 1.5 in your sns.lineplot() functions. You can find additional possible arguments in the documentations linked. Example output on random data: seaborn.lineplot() without linewdith argument provided seaborn.lineplot() with linewidth = 3


Question:
How to plot multiple bars grouped How to plot multiple bars in matplotlib, when I tried to call the bar function multiple times, they overlap and as seen the below figure the highest value red can be seen only. How can I plot the multiple bars with dates on the x-axes? So far, I tried this:
```py
import matplotlib.pyplot as plt
import datetime

x = [
    datetime.datetime(2011, 1, 4, 0, 0),
    datetime.datetime(2011, 1, 5, 0, 0),
    datetime.datetime(2011, 1, 6, 0, 0)
]
y = [4, 9, 2]
z = [1, 2, 3]
k = [11, 12, 13]

ax = plt.subplot(111)
ax.bar(x, y, width=0.5, color='b', align='center')
ax.bar(x, z, width=0.5, color='g', align='center')
ax.bar(x, k, width=0.5, color='r', align='center')
ax.xaxis_date()

plt.show()
```
I got this: The results should be something like, but with the dates are on the x-axes and bars are next to each other:

Response:
```
import matplotlib.pyplot as plt
from matplotlib.dates import date2num
import datetime

x = [
    datetime.datetime(2011, 1, 4, 0, 0),
    datetime.datetime(2011, 1, 5, 0, 0),
    datetime.datetime(2011, 1, 6, 0, 0)
]
x = date2num(x)

y = [4, 9, 2]
z = [1, 2, 3]
k = [11, 12, 13]

ax = plt.subplot(111)
ax.bar(x-0.2, y, width=0.2, color='b', align='center')
ax.bar(x, z, width=0.2, color='g', align='center')
ax.bar(x+0.2, k, width=0.2, color='r', align='center')
ax.xaxis_date()

plt.show()
```
I don't know what's the "y values are also overlapping" means, does the following code solve your problem?
```
ax = plt.subplot(111)
w = 0.3
ax.bar(x-w, y, width=w, color='b', align='center')
ax.bar(x, z, width=w, color='g', align='center')
ax.bar(x+w, k, width=w, color='r', align='center')
ax.xaxis_date()
ax.autoscale(tight=True)

plt.show()
```


Question:
Specify color of each point in 3d scatter plot I have a 3D Plot that I created using matplotlib, and I have a list of rbg values that correspond to each point. I have the X, Y, and Z data, and then I have a "color list" of the form:
```
[ (r,g,b), (r,g,b), ... , (r,g,b) ]
```
to match each (x, y, z) point. Right now, I have
```
fig = plt.figure()
ax = fig.add_subplot(111, projection = '3d')

ax.scatter(X, Y, Z)
plt.show()
```
What's the appropriate way to incorporate those rgb tuples so that each point will be assigned a specific color?

Response:
If you don't want to use a for loop (which can be very slow for large lists) You can use the scatter command as is with an RGB color list, but you need to specify the colors as a vector of RGB (or RGBA) values between 0 and 1
```
X = [0, 1, 2]
Y = [0, 1, 2]
Z = [0, 1, 2]
C = np.array([[255, 0, 0], [0, 255, 0], [0, 0, 255]])
fig = plt.figure()
ax = fig.add_subplot(111, projection = '3d')

ax.scatter(X, Y, Z, c = C/255.0)
plt.show()
```


Question:
Plotting a time series? I have a data set which has dates in the first column, and a "result" integer which is either 1 or 0. The date column was successfully converted to a time object. I tried to plot the values directly using matplotlib's plot function, but that did not work.. Sample:
```none
Date       Result
2017-01-06     0.0
2017-01-06     1.0
2017-01-06     0.0
2017-01-07     0.0
2017-01-07     0.0
```
I tried using df.plot(), but the resulting plot has very undesirable results. What I want at the end of the day is dates on the x axis, and the "result" on the y axis. Where am I going wrong? What's wrong with what I'm doing?

Response: Please use df.set_index('Date').plot() or df.plot(x='Date', y='Result') because of the plot by default use index of df as the x-axis, so you should set the 'Date' column as the index, or specify which column to use as the x-axis. see more at pandas.DataFrame.plot


Question: Command-line Unix ASCII-based charting / plotting tool Is there a good command-line UNIX charting / graphing / plotting tool out there? I'm looking for something that will plot xy points on an ASCII graph. Just to clarify, I'm looking for something that will output a graph in ASCII (like ascii-art style), so I can use it over an interactive shell session without needing X.

Response:
Try gnuplot. It has very powerful graphing possibilities. It can output to your terminal in the following way:
```
gnuplot> set terminal dumb
Terminal type set to 'dumb'
Options are 'feed 79 24'
gnuplot> plot sin(x)

   1 ++----------------**---------------+----**-----------+--------**-----++
     +                *+ *              +   *  *          +  sin(x) ****** +
 0.8 ++              *    *                *    *                *    *   ++
     |               *    *                *    *                *    *    |
 0.6 ++              *     *              *      *              *      *  ++
     *              *       *             *       *             *      *   |
 0.4 +*             *       *             *       *             *      *  ++
     |*            *        *            *        *            *        *  |
 0.2 +*            *        *            *        *            *        * ++
     | *          *          *          *          *          *          * |
   0 ++*          *          *          *          *          *          *++
     |  *         *           *         *           *         *           *|
-0.2 ++ *         *           *         *           *         *           *+
     |   *       *            *        *            *        *            *|
-0.4 ++  *       *            *        *            *        *            *+
     |   *      *              *      *              *      *              *
-0.6 ++  *      *              *      *              *      *             ++
     |    *     *               *     *               *    *               |
-0.8 ++    *   *                 *   *                *    *              ++
     +     *  *        +         *  *   +              *  *                +
  -1 ++-----**---------+----------**----+---------------**+---------------++
    -10               -5                0                 5                10
```


Question:
How to plot a 2d matrix in python with colorbar? (like imagesc in Matlab) In Matlab I can visualize a matrix data quite easily with
```
data = rand(10,10); % Createas a 10 x 10 random matrix
imagesc(data);
colorbar;
```
Now I want to do the same thing in python. I already know how to plot a 2d matrix (numpy array):
```
from matplotlib.pyplot import imshow
import numpy as np
data = np.random.random((10,10))
imshow(np.asarray(img))
```
but I don't know how to add a colorbar to it. Any ideas?

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

plt.imshow(np.random.random((50,50)))
plt.colorbar()
plt.show()
```


Question:
Adding a matplotlib legend How can one create a legend for a line graph in Matplotlib's PyPlot without creating any extra variables? Please consider the graphing script below:
```py
if __name__ == '__main__':
    PyPlot.plot(length, bubble, 'b-',
                length, ins, 'r-',
                length, merge_r, 'g+',
                length, merge_i, 'p-', )
    PyPlot.title("Combined Statistics")
    PyPlot.xlabel("Length of list (number)")
    PyPlot.ylabel("Time taken (seconds)")
    PyPlot.show()
```
As you can see, this is a very basic use of matplotlib's PyPlot. This generates the following graph: However, it is unclear which line is which. Thus, I need a legend; however, taking a look at the following example below (from the official site):
```
ax = subplot(1,1,1)
p1, = ax.plot([1,2,3], label="line 1")
p2, = ax.plot([3,2,1], label="line 2")
p3, = ax.plot([2,3,1], label="line 3")

handles, labels = ax.get_legend_handles_labels()

# reverse the order
ax.legend(handles[::-1], labels[::-1])

# or sort them by labels
import operator
hl = sorted(zip(handles, labels), key=operator.itemgetter(1))
handles2, labels2 = zip(*hl)

ax.legend(handles2, labels2)
```
You will see that I need to create an extra variable ax. How can I add a legend to my graph without having to create this extra variable and retaining the simplicity of my current script?

Response:
Add a label= to each of your plot() calls, and then call legend(loc='upper left'). Consider this sample (tested with Python 3.8.0):
```
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 20, 1000)
y1 = np.sin(x)
y2 = np.cos(x)

plt.plot(x, y1, "-b", label="sine")
plt.plot(x, y2, "-r", label="cosine")
plt.legend(loc="upper left")
plt.ylim(-1.5, 2.0)
plt.show()
```
Slightly modified from this tutorial: http://jakevdp.github.io/mpl_tutorial/tutorial_pages/tut1.html


Question: Plot Ellipse with matplotlib.pyplot Sorry if this is a stupid question, but is there an easy way to plot an ellipse with matplotlib.pyplot in Python? I was hoping there would be something similar to matplotlib.pyplot.arrow, but I can't find anything. Is the only way to do it using matplotlib.patches with draw_artist or something similar? I would hope that there is a simpler method, but the documentation doesn't offer much help.

Response:
If you do not want to use a patch, you can use the parametric equation of an ellipse: x = u + a cos(t) ; y = v + b sin(t)
```
import numpy as np
from matplotlib import pyplot as plt
from math import pi

u=1.     #x-position of the center
v=0.5    #y-position of the center
a=2.     #radius on the x-axis
b=1.5    #radius on the y-axis

t = np.linspace(0, 2*pi, 100)
plt.plot( u+a*np.cos(t) , v+b*np.sin(t) )
plt.grid(color='lightgray',linestyle='--')
plt.show()
```
Which gives: The ellipse can be rotated thanks to a 2D-rotation matrix :
```
import numpy as np
from matplotlib import pyplot as plt
from math import pi, cos, sin

u=1.       #x-position of the center
v=0.5      #y-position of the center
a=2.       #radius on the x-axis
b=1.5      #radius on the y-axis
t_rot=pi/4 #rotation angle

t = np.linspace(0, 2*pi, 100)
Ell = np.array([a*np.cos(t) , b*np.sin(t)])
     #u,v removed to keep the same center location
R_rot = np.array([[cos(t_rot) , -sin(t_rot)],[sin(t_rot) , cos(t_rot)]])
     #2-D rotation matrix

Ell_rot = np.zeros((2,Ell.shape[1]))
for i in range(Ell.shape[1]):
    Ell_rot[:,i] = np.dot(R_rot,Ell[:,i])

plt.plot( u+Ell[0,:] , v+Ell[1,:] )     #initial ellipse
plt.plot( u+Ell_rot[0,:] , v+Ell_rot[1,:],'darkorange' )    #rotated ellipse
plt.grid(color='lightgray',linestyle='--')
plt.show()
```
Returns:


Question: How do you set the absolute position of figure windows with matplotlib? I'm writing a simple Python application that uses matplotlib to display a few figures on screen. The number of figures generated is based on user input and changes throughout the application's life. The user has the ability to issue a "plot" command to generate a new figure window with the selected data series. In order to improve the user experience, I would like to provide another command that would programmatically arrange all open figure windows in some convenient arrangement (e.g. tile them across the available screen space). I believe to have found APIs that allow me to adjust the size of the figure window (in pixels), but haven't had any success in finding a way to set their absolute position on screen. Is there a way to do this without delving into the details of whatever backend is in use? I would like to do this in a backend-agnostic way so I can avoid relying upon implementation details that might change in the future.

Response:
Found the solution for QT backend:
```
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
mngr = plt.get_current_fig_manager()
# to put it into the upper left corner for example:
mngr.window.setGeometry(50,100,640, 545)
```
If one doesn't know the x- and y-width one can read them out first, like so:
```
# get the QTCore PyRect object
geom = mngr.window.geometry()
x,y,dx,dy = geom.getRect()
```
and then set the new position with the same size:
```
mngr.window.setGeometry(newX, newY, dx, dy)
```


Question:
Change title and colorbar text and tick colors I wanted to know how to change the color of the ticks in the colorbar and how to change the font color of the title and colorbar in a figure. For example, things obviously are visible in temp.png but not in temp2.png:
```
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import randn

fig = plt.figure()
data = np.clip(randn(250,250),-1,1)
cax = plt.imshow(data, interpolation='nearest')
plt.title('my random fig')
plt.colorbar()

# works fine
plt.savefig('temp.png')
# title and colorbar ticks and text hidden
plt.savefig('temp2.png', facecolor="black", edgecolor="none")
```
Thanks

Response:
Previous answer didnt give what I wanted. This is how I did it:
```
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import randn
data = np.clip(randn(250,250),-1,1)
data = np.ma.masked_where(data > 0.5, data)

fig, ax1 = plt.subplots(1,1)

im = ax1.imshow(data, interpolation='nearest')
cb = plt.colorbar(im)

fg_color = 'white'
bg_color = 'black'

# IMSHOW
# set title plus title color
ax1.set_title('ax1 title', color=fg_color)

# set figure facecolor
ax1.patch.set_facecolor(bg_color)

# set tick and ticklabel color
im.axes.tick_params(color=fg_color, labelcolor=fg_color)

# set imshow outline
for spine in im.axes.spines.values():
    spine.set_edgecolor(fg_color)

# COLORBAR
# set colorbar label plus label color
cb.set_label('colorbar label', color=fg_color)

# set colorbar tick color
cb.ax.yaxis.set_tick_params(color=fg_color)

# set colorbar edgecolor
cb.outline.set_edgecolor(fg_color)

# set colorbar ticklabels
plt.setp(plt.getp(cb.ax.axes, 'yticklabels'), color=fg_color)

fig.patch.set_facecolor(bg_color)
plt.tight_layout()
plt.show()
#plt.savefig('save/to/pic.png', dpi=200, facecolor=bg_color)
```


Question:
Matplotlib returning a plot object I have a function that wraps pyplot.plt so I can quickly create graphs with oft-used defaults:
```
def plot_signal(time, signal, title='', xlab='', ylab='',
                line_width=1, alpha=1, color='k',
                subplots=False, show_grid=True, fig_size=(10, 5)):

    # Skipping a lot of other complexity here

    f, axarr = plt.subplots(figsize=fig_size)
    axarr.plot(time, signal, linewidth=line_width,
               alpha=alpha, color=color)
    axarr.set_xlim(min(time), max(time))
    axarr.set_xlabel(xlab)
    axarr.set_ylabel(ylab)
    axarr.grid(show_grid)

    plt.suptitle(title, size=16)
    plt.show()
```
However, there are times where I'd want to be able to return the plot so I can manually add/edit things for a specific graph. For example, I want to be able to change the axis labels, or add a second line to the plot after calling the function:
```
import numpy as np

x = np.random.rand(100)
y = np.random.rand(100)

plot = plot_signal(np.arange(len(x)), x)

plot.plt(y, 'r')
plot.show()
```
I've seen a few questions on this (How to return a matplotlib.figure.Figure object from Pandas plot function? and AttributeError: 'Figure' object has no attribute 'plot') and as a result I've tried adding the following to the end of the function: return axarr return axarr.get_figure() return plt.axes() However, they all return a similar error: AttributeError: 'AxesSubplot' object has no attribute 'plt' Whats the correct way to return a plot object so it can be edited later?

Response:
I think the error is pretty self-explanatory. There is no such thing as pyplot.plt, or similar. plt is the quasi-standard abbreviated form of pyplot when being imported, i.e., import matplotlib.pyplot as plt. Concerning the problem, the first approach, return axarr is the most versatile one. You get an axis, or an array of axes, and can plot to it. The code may look like:
```
def plot_signal(x,y, ..., **kwargs):
    # Skipping a lot of other complexity here
    f, ax = plt.subplots(figsize=fig_size)
    ax.plot(x,y, ...)
    # further stuff
    return ax

ax = plot_signal(x,y, ...)
ax.plot(x2, y2, ...)
plt.show()
```


Question:
Plotting numerous disconnected line segments with different colors I have a set of data records like this:
```
(s1, t1), (u1, v1), color1
(s2, t2), (u2, v2), color2
.
.
.
(sN, tN), (uN, vN), colorN
```
In any record, the first two values are the end-points of a line segment, the third value is the color of that line segment. More specifically, (sn, tn) are the x-y coordinates of the first end-point, (un, vn) are the x-y coordinates of the second-endpoint. Also, color is an rgb with alpha value. In general, any two line segments are disconnected (meaning that their end-points do not necessarily coincide). How to plot this data using matplotlib with a single plot call (or as few as possible) as there could be potentially thousands of records. Attempts Preparing the data in one big list and calling plot against it is way too slow. For example the following code couldn't finish in a reasonable amount of time:
```
import numpy as np
import matplotlib.pyplot as plt

data = []
for _ in xrange(60000):
    data.append((np.random.rand(), np.random.rand()))
    data.append((np.random.rand(), np.random.rand()))
    data.append('r')

print 'now plotting...' # from now on, takes too long
plt.plot(*data)
print 'done'
#plt.show()
```
I was able to speed-up the plot rendering by using the None insertion trick as follows:
```
import numpy as np
import matplotlib.pyplot as plt
from timeit import timeit

N = 60000
_s = np.random.rand(N)
_t = np.random.rand(N)
_u = np.random.rand(N)
_v = np.random.rand(N)
x = []
y = []
for s, t, u, v in zip(_s, _t, _u, _v):
    x.append(s)
    x.append(u)
    x.append(None)
    y.append(t)
    y.append(v)
    y.append(None)
print timeit(lambda:plt.plot(x, y), number=1)
```
This executes in under a second on my machine. I still have to figure out how to embed the color values (RGB with alpha channel).

Response:
use LineCollection:
```
import numpy as np
import pylab as pl
from matplotlib import collections  as mc

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

lc = mc.LineCollection(lines, colors=c, linewidths=2)
fig, ax = pl.subplots()
ax.add_collection(lc)
ax.autoscale()
ax.margins(0.1)
```
here is the output:


Question:
Dollar Sign with Thousands Comma Tick Labels Given the following bar chart:
```
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({'A': ['A', 'B'], 'B': [1000,2000]})

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

df.plot(kind='bar', x='A', y='B',
        align='center', width=.5, edgecolor='none',
        color='grey', ax=ax)
plt.xticks(rotation=25)
plt.show()
```
I'd like to display the y-tick labels as thousands of dollars like this: $2,000 I know I can use this to add a dollar sign:
```
import matplotlib.ticker as mtick
fmt = '$%.0f'
tick = mtick.FormatStrFormatter(fmt)
ax.yaxis.set_major_formatter(tick)
```
...and this to add a comma:
```
ax.get_yaxis().set_major_formatter(
     mtick.FuncFormatter(lambda x, p: format(int(x), ',')))
```
...but how do I get both?

Response:
You can use StrMethodFormatter, which uses the str.format() specification mini-language.
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick

df = pd.DataFrame({'A': ['A', 'B'], 'B': [1000,2000]})

fig, ax = plt.subplots(1, 1, figsize=(2, 2))
df.plot(kind='bar', x='A', y='B',
        align='center', width=.5, edgecolor='none',
        color='grey', ax=ax)

fmt = '${x:,.0f}'
tick = mtick.StrMethodFormatter(fmt)
ax.yaxis.set_major_formatter(tick)
plt.xticks(rotation=25)

plt.show()
```


Question: matplotlib analog of R's `pairs` R has a useful function pairs that provides nice matrix of plots of pairwise connections between variables in a data set. The resulting plot looks similar to the following figure, copied from this blog post: Is there any ready to use function based on python's matplolib? I have searched its gallery, but couldn't find anything that resembles what I need. Technically, this should be a simple task, but proper handling of all the possible cases, labels, titles, etc is very tedious. UPDATE see below my answer with a quick and dirty approximation.

Response:
Pandas has a built in function scatter_matrix (source code) which is something like this.
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(np.random.randn(1000, 4), columns=['A','B','C','D'])
axes = pd.tools.plotting.scatter_matrix(df, alpha=0.2)
plt.tight_layout()
plt.savefig('scatter_matrix.png')
```
However it is pandas specific (but could be used as a starting point). There are some more R like plots in pandas. Have a look at the docs.


Question:
Change the relative size of a subplot I have two plots
```
import matplotlib.pyplot as plt
plt.subplot(121)
plt.subplot(122)
```
I want plt.subplot(122) to be half as wide as plt.subplot(121). Is there a straightforward way to set the height and width parameters for a subplot?

Response:
See the grid-spec tutorial: http://matplotlib.sourceforge.net/users/gridspec.html Example code:
```
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

f = plt.figure()

gs = gridspec.GridSpec(1, 2,width_ratios=[2,1])

ax1 = plt.subplot(gs[0])
ax2 = plt.subplot(gs[1])

plt.show()
```
You can also adjust the height ratio using a similar option in GridSpec


Question:
Split title of a figure in matplotlib into multiple lines I use matplotlib to create a figure with 4 sub-plots in it. I would like to split one of my title of a subplot, such that each line would be in the centered with respect to subplot. I tried
```
import matplotlib.pylab as plt

fig = plt.figure(num=0,figsize=(8.27, 11.69), dpi=300)
ax  = fig.add_subplot(2, 2, 1)
ax.set_title(r'Normalized occupied \\ Neighbors')
```
and what I get is that Neighbors is indented to the left side. How could I correct this?

Response:
I get the correct alignment when I format the string this way:
```
import matplotlib.pylab as plt

fig = plt.figure()#num=0,figsize=(8.27, 11.69), dpi=300)
ax  = fig.add_subplot(2, 2, 1)
ax.set_title('Normalized occupied \n Neighbors')

plt.show()
```


Question:
Creating a Confidence Ellipse in a scatterplot using matplotlib How do I create a confidence ellipse in a scatterplot using matplotlib? The following code works until creating scatter plot. Then, is anyone familiar with putting confidence ellipses over the scatter plot?
```
import numpy as np
import matplotlib.pyplot as plt
x = [5,7,11,15,16,17,18]
y = [8, 5, 8, 9, 17, 18, 25]

plt.scatter(x,y)
plt.show()
```
Following is the reference for Confidence Ellipses from SAS. http://support.sas.com/documentation/cdl/en/grstatproc/62603/HTML/default/viewer.htm#a003160800.htm The code in sas is like this:
```
proc sgscatter data=sashelp.iris(where=(species="Versicolor"));
  title "Versicolor Length and Width";
  compare y=(sepalwidth petalwidth)
          x=(sepallength petallength)
          / reg ellipse=(type=mean) spacing=4;
run;
```

Response:
After giving the accepted answer a go, I found that it doesn't choose the quadrant correctly when calculating theta, as it relies on np.arccos: Taking a look at the 'possible duplicate' and Joe Kington's solution on github, I watered his code down to this:
```
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse

def eigsorted(cov):
    vals, vecs = np.linalg.eigh(cov)
    order = vals.argsort()[::-1]
    return vals[order], vecs[:,order]

x = [5,7,11,15,16,17,18]
y = [25, 18, 17, 9, 8, 5, 8]

nstd = 2
ax = plt.subplot(111)

cov = np.cov(x, y)
vals, vecs = eigsorted(cov)
theta = np.degrees(np.arctan2(*vecs[:,0][::-1]))
w, h = 2 * nstd * np.sqrt(vals)
ell = Ellipse(xy=(np.mean(x), np.mean(y)),
              width=w, height=h,
              angle=theta, color='black')
ell.set_facecolor('none')
ax.add_artist(ell)
plt.scatter(x, y)
plt.show()
```


Question:
How do I change the range of the x-axis with datetime? I'm trying to plot a graph of dates on the x-axis and values on the y-axis. It works fine, except that I can't get the range of the x-axis to be appropriate. The x-axis range is always Jan 2012 to Jan 2016, despite my dates being from today. I am even specifying that xlim should be the first and last date. I'm writing this for python-django, if that's relevant.
```
import datetime
 import matplotlib.pyplot as plt

 x = [datetime.date(2014, 1, 29), datetime.date(2014, 1, 29), datetime.date(2014, 1, 29)]
 y = [2, 4, 1]

 fig, ax = plt.subplots()
 ax.plot_date(x, y)
 ax.set_xlim([x[0], x[-1]])

 canvas = FigureCanvas(plt.figure(1))
 response = HttpResponse(content_type='image/png')
 canvas.print_png(response)
 return response
```
And here is the output:

Response:
Edit: Having seen actual data from the OP, all of the values are at the same date/time. So matplotlib is automatically zooming the x-axis out. You can still manually set the x-axis limits with datetime objects If I do something like this on matplotlib v1.3.1:
```
import datetime
import matplotlib.pyplot as plt

x = [datetime.date(2014, 1, 29)] * 3
y = [2, 4, 1]

fig, ax = plt.subplots()
ax.plot_date(x, y, markerfacecolor='CornflowerBlue', markeredgecolor='white')
fig.autofmt_xdate()
ax.set_xlim([datetime.date(2014, 1, 26), datetime.date(2014, 2, 1)])
ax.set_ylim([0, 5])
```
I get: And the axes limits match the dates that I specified.


Question: Y-Axis ticks on Right Side of Plot I have a simple line plot and need to move the y-axis ticks from the (default) left side of the plot to the right side. Any thoughts on how to do this?

Response:
Use ax.yaxis.tick_right() for example:
```
from matplotlib import pyplot as plt

f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
plt.plot([2,3,4,5])
plt.show()
```


Question: Dynamically updating plot in matplotlib I am making an application in Python which collects data from a serial port and plots a graph of the collected data against arrival time. The time of arrival for the data is uncertain. I want the plot to be updated when data is received. I searched on how to do this and found two methods: Clear the plot and re-draw the plot with all the points again. Animate the plot by changing it after a particular interval. I do not prefer the first one as the program runs and collects data for a long time (a day for example), and redrawing the plot will be pretty slow. The second one is also not preferable as time of arrival of data is uncertain and I want the plot to update only when the data is received. Is there a way in which I can update the plot just by adding more points to it only when the data is received?

Response:
Is there a way in which I can update the plot just by adding more point[s] to it... There are a number of ways of animating data in matplotlib, depending on the version you have. Have you seen the animation examples in the matplotlib documentation? The animation API defines a function FuncAnimation which animates a function in time. This function could just be the function you use to acquire your data. Each method basically sets the data property of the object being drawn, so doesn't require clearing the screen or figure. The data property can simply be extended, so you can keep the previous points and just keep adding to your line (or image or whatever you are drawing). Given that you say that your data arrival time is uncertain your best bet is probably just to do something like:
```
import matplotlib.pyplot as plt
import numpy

hl, = plt.plot([], [])

def update_line(hl, new_data):
    hl.set_xdata(numpy.append(hl.get_xdata(), new_data))
    hl.set_ydata(numpy.append(hl.get_ydata(), new_data))
    plt.draw()
```
Then when you receive data from the serial port just call update_line.


Question: How to draw intersecting planes? I want to use matplotlib to draw more or less the figure I attached below, which includes the two intersecting planes with the right amount of transparency indicating their relative orientations, and the circles and vectors in the two planes projected in 2D. I'm not sure if there is an existing package for doing this, any hints?

Response:
```
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np

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

dim = 10

X, Y = np.meshgrid([-dim, dim], [-dim, dim])
Z = np.zeros((2, 2))

angle = .5
X2, Y2 = np.meshgrid([-dim, dim], [0, dim])
Z2 = Y2 * angle
X3, Y3 = np.meshgrid([-dim, dim], [-dim, 0])
Z3 = Y3 * angle

r = 7
M = 1000
th = np.linspace(0, 2 * np.pi, M)

x, y, z = r * np.cos(th),  r * np.sin(th), angle * r * np.sin(th)

ax.plot_surface(X2, Y3, Z3, color='blue', alpha=.5, linewidth=0, zorder=-1)

ax.plot(x[y < 0], y[y < 0], z[y < 0], lw=5, linestyle='--', color='green',
        zorder=0)

ax.plot_surface(X, Y, Z, color='red', alpha=.5, linewidth=0, zorder=1)

ax.plot(r * np.sin(th), r * np.cos(th), np.zeros(M), lw=5, linestyle='--',
        color='k', zorder=2)

ax.plot_surface(X2, Y2, Z2, color='blue', alpha=.5, linewidth=0, zorder=3)

ax.plot(x[y > 0], y[y > 0], z[y > 0], lw=5, linestyle='--', color='green',
        zorder=4)

plt.axis('off')
plt.show()
```
caveats: I am running a version very close to the current master, so I am not sure what will work in older versions The reason for splitting up the plotting is that 'above' and 'below' are determined in a some what arcane way (I am not strictly sure the zorder actually does anything), and is really dependent on the order the artists are drawn in. Thus surfaces can not intersect (one will be above the other every where), so you need to plot the sections on either side of the intersection separately. (You can see this in the black line which I didn't split at looks like it in 'on top of' the upper blue plane). The 'proper' ordering of the surfaces also seems to be dependent on the view angle.


Question:
matplotlib not showing first label on x axis for the Bar Plot Here is the code I am working on to create a logarithmic bar plot
```
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize = (12,6))

ax = fig.add_subplot(111)

x = ['Blue Whale', 'Killer Whale', 'Bluefin tuna', \
     'Bottlenose dolphin', "Maui's dolphin", 'Flounder',\
     'Starfish', 'Spongebob Squarepants']

y = [190000, 5987, 684, 650, 40, 6.8, 5, 0.02]

ax.bar(np.arange(len(x)),y, log=1)

ax.set_xticklabels(x, rotation = 45)

fig.savefig(filename = "f:/plot.png")
```
Now this is creating the bar plot where its not showing the first label, which is Blue Whale. Here is the plot I am getting So how can this be rectified ? Matplotlib version is 2.0.0 and Numpy version is 1.12.1 Thanks

Response:
In matplotlib 2.0 there might be unshown tickmarks at the edges of the axes. To be on the safe side, you can set the tick locations in addition to the tick labels,
```
ax.set_xticks(np.arange(len(x)))
ax.set_xticklabels(x, rotation = 45)
```
You may also want to set the labels to align to their right edge, if they're rotated:
```
ax.set_xticklabels(x, rotation = 45, ha="right")
```


Question:
How do I plot a step function? This should be easy but I have just started toying with matplotlib and python. I can do a line or a scatter plot but i am not sure how to do a simple step function. Any help is much appreciated.
```
x = 1,2,3,4
y = 0.002871972681775004, 0.00514787917410944, 0.00863476098280219, 0.012003316194034325
```

Response:
It seems like you want step. E.g.
```
import matplotlib.pyplot as plt

x = [1,2,3,4]
y = [0.002871972681775004, 0.00514787917410944,
     0.00863476098280219, 0.012003316194034325]

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


Question:
unique plot marker for each plot I have a loop where i create some plots and I need unique marker for each plot. I think about creating function, which returns random symbol, and use it in my program in this way:
```
for i in xrange(len(y)):
    plt.plot(x, y [i], randomMarker())
```
but I think this way is not good one. I need this just to distinguish plots on legend, because plots must be not connected with lines, they must be just sets of dots.

Response:
itertools.cycle will iterate over a list or tuple indefinitely. This is preferable to a function which randomly picks markers for you. Python 2.x
```
import itertools
marker = itertools.cycle((',', '+', '.', 'o', '*'))
for n in y:
    plt.plot(x,n, marker = marker.next(), linestyle='')
```
Python 3.x
```
import itertools
marker = itertools.cycle((',', '+', '.', 'o', '*'))
for n in y:
    plt.plot(x,n, marker = next(marker), linestyle='')
```
You can use that to produce a plot like this (Python 2.x):
```
import numpy as np
import matplotlib.pyplot as plt
import itertools

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

marker = itertools.cycle((',', '+', '.', 'o', '*'))

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

for q,p in zip(x,y):
    ax.plot(q,p, linestyle = '', marker=marker.next())

plt.show()
```


Question:
Why is set_xlim() not setting the x-limits in my figure? I'm plotting some data with matplotlib. I want the plot to focus on a specific range of x-values, so I'm using set_xlim(). Roughly, my code looks like this:
```
fig=plt.figure()
ax=fig.add_subplot(111)
for ydata in ydatalist:
    ax.plot(x_data,y_data[0],label=ydata[1])
ax.set_xlim(left=0.0,right=1000)
plt.savefig(filename)
```
When I look at the plot, the x range ends up being from 0 to 12000. This occurs whether set_xlim() occurs before or after plot(). Why is set_xlim() not working in this situation?

Response:
The text of this answer was taken from an answer that was deleted almost immediately after it was posted. set_xlim() limits the data that is displayed on the plot. In order to change the bounds of the axis, use set_xbound().
```
fig=plt.figure()
ax=fig.add_subplot(111)
ax.plot(x_data,y_data)
ax.set_xbound(lower=0.0, upper=1000)
plt.savefig(filename)
```


Question:
Display multiple images in subplots How do I use the matlib function plt.imshow(image) to display multiple images? For example my code is as follows:
```
for file in images:
    process(file)

def process(filename):
    image = mpimg.imread(filename)
    <something gets done here>
    plt.imshow(image)
```
My results show that only the last processed image is shown effectively overwriting the other images

Response:
To display the multiple images use subplot()
```
plt.figure()

#subplot(r,c) provide the no. of rows and columns
f, axarr = plt.subplots(4,1)

# use the created array to output your multiple images. In this case I have stacked 4 images vertically
axarr[0].imshow(v_slice[0])
axarr[1].imshow(v_slice[1])
axarr[2].imshow(v_slice[2])
axarr[3].imshow(v_slice[3])
```


Question:
iPython/Jupyter Notebook and Pandas, how to plot multiple graphs in a for loop? Consider the following code running in iPython/Jupyter Notebook:
```
from pandas import *
%matplotlib inline

ys = [[0,1,2,3,4],[4,3,2,1,0]]
x_ax = [0,1,2,3,4]

for y_ax in ys:
    ts = Series(y_ax,index=x_ax)
    ts.plot(kind='bar', figsize=(15,5))
```
I would expect to have 2 separate plots as output, instead, I get the two series merged in one single plot. Why is that? How can I get two separate plots keeping the for loop?

Response:
Just add the call to plt.show() after you plot the graph (you might want to import matplotlib.pyplot to do that), like this:
```
from pandas import Series
import matplotlib.pyplot as plt
%matplotlib inline

ys = [[0,1,2,3,4],[4,3,2,1,0]]
x_ax = [0,1,2,3,4]

for y_ax in ys:
    ts = Series(y_ax,index=x_ax)
    ts.plot(kind='bar', figsize=(15,5))
    plt.show()
```


Question: Saving interactive Matplotlib figures Is there a way to save a Matplotlib figure such that it can be re-opened and have typical interaction restored? (Like the .fig format in MATLAB?) I find myself running the same scripts many times to generate these interactive figures. Or I'm sending my colleagues multiple static PNG files to show different aspects of a plot. I'd rather send the figure object and have them interact with it themselves.

Response:
I just found out how to do this. The "experimental pickle support" mentioned by @pelson works quite well. Try this:
```
# Plot something
import matplotlib.pyplot as plt
fig,ax = plt.subplots()
ax.plot([1,2,3],[10,-10,30])
```
After your interactive tweaking, save the figure object as a binary file:
```
import pickle
pickle.dump(fig, open('FigureObject.fig.pickle', 'wb')) # This is for Python 3 - py2 may need `file` instead of `open`
```
Later, open the figure and the tweaks should be saved and GUI interactivity should be present:
```
import pickle
figx = pickle.load(open('FigureObject.fig.pickle', 'rb'))

figx.show() # Show the figure, edit it, etc.!
```
You can even extract the data from the plots:
```
data = figx.axes[0].lines[0].get_data()
```
(It works for lines, pcolor & imshow - pcolormesh works with some tricks to reconstruct the flattened data.) I got the excellent tip from Saving Matplotlib Figures Using Pickle.


Question:
multi index plotting I have some data where I've manipulated the dataframe using the following code:
```
import pandas as pd
import numpy as np

data = pd.DataFrame([[0,0,0,3,6,5,6,1],[1,1,1,3,4,5,2,0],[2,1,0,3,6,5,6,1],[3,0,0,2,9,4,2,1],[4,0,1,3,4,8,1,1],[5,1,1,3,3,5,9,1],[6,1,0,3,3,5,6,1],[7,0,1,3,4,8,9,1]], columns=["id", "sex", "split", "group0Low", "group0High", "group1Low", "group1High", "trim"])
data

#remove all where trim == 0
trimmed = data[(data.trim == 1)]
trimmed

#create df with columns to be split
columns = ['group0Low', 'group0High', 'group1Low', 'group1High']
to_split = trimmed[columns]
to_split

level_group = np.where(to_split.columns.str.contains('0'), 0, 1)
# output: array([0, 0, 1, 1])
level_low_high = np.where(to_split.columns.str.contains('Low'), 'low', 'high')
# output: array(['low', 'high', 'low', 'high'], dtype='<U4')

multi_level_columns = pd.MultiIndex.from_arrays([level_group, level_low_high], names=['group', 'val'])
to_split.columns = multi_level_columns
to_split.stack(level='group')

sex = trimmed['sex']
split = trimmed['split']
horizontalStack = pd.concat([sex, split, to_split], axis=1)
horizontalStack

finalData = horizontalStack.groupby(['split', 'sex', 'group'])
finalData.mean()
```
My question is, how do I plot the mean data using ggplot or seaborn such that for each "split" level I get a graph that looks like this: At the bottom of the code you can see I've tried to split up the group factor so I can separate the bars, but that resulted in an error (KeyError: 'group') and I think that is related to the way I used multi indexing

Response:
I would use a factor plot from seaborn. Say you have data like this:
```
import numpy as np
import pandas

import seaborn
seaborn.set(style='ticks')
np.random.seed(0)

groups = ('Group 1', 'Group 2')
sexes = ('Male', 'Female')
means = ('Low', 'High')
index = pandas.MultiIndex.from_product(
    [groups, sexes, means],
   names=['Group', 'Sex', 'Mean']
)

values = np.random.randint(low=20, high=100, size=len(index))
data = pandas.DataFrame(data={'val': values}, index=index).reset_index()
print(data)

     Group     Sex  Mean  val
0  Group 1    Male   Low   64
1  Group 1    Male  High   67
2  Group 1  Female   Low   84
3  Group 1  Female  High   87
4  Group 2    Male   Low   87
5  Group 2    Male  High   29
6  Group 2  Female   Low   41
7  Group 2  Female  High   56
```
You can then create the factor plot with one command + plus an extra line to remove some redundant (for your data) x-labels:
```
# Note: catplot used to be called factorplot
fg = seaborn.catplot(x='Group', y='val', hue='Mean',
                        col='Sex', data=data, kind='bar')
fg.set_xlabels('')
```
Which gives me:


Question:
How to decrease density of tick labels in subplots I'm looking to decrease density of tick labels on differing subplot
```
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from StringIO import StringIO
data = """\
    a   b   c   d
z   54.65   6.27    19.53   4.54
w   -1.27   4.41    11.74   3.06
d   5.51    3.39    22.98   2.29
t   76284.53    -0.20   28394.93    0.28
"""
df = pd.read_csv(StringIO(data), sep='\s+')
gs = gridspec.GridSpec(3, 1,height_ratios=[1,1,4] )
ax0 = plt.subplot(gs[0])
ax1 = plt.subplot(gs[1])
ax2 = plt.subplot(gs[2])
df.plot(kind='bar', ax=ax0,color=('Blue','DeepSkyBlue','Red','DarkOrange'))
df.plot(kind='bar', ax=ax1,color=('Blue','DeepSkyBlue','Red','DarkOrange'))
df.plot(kind='bar', ax=ax2,color=('Blue','DeepSkyBlue','Red','DarkOrange'),rot=45)
ax0.set_ylim(69998, 78000)
ax1.set_ylim(19998, 29998)
ax2.set_ylim(-2, 28)
ax0.legend().set_visible(False)
ax1.legend().set_visible(False)
ax2.legend().set_visible(False)
ax0.spines['bottom'].set_visible(False)
ax1.spines['bottom'].set_visible(False)
ax1.spines['top'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax0.xaxis.set_ticks_position('none')
ax1.xaxis.set_ticks_position('none')
ax0.xaxis.set_label_position('top')
ax1.xaxis.set_label_position('top')
ax0.tick_params(labeltop='off')
ax1.tick_params(labeltop='off', pad=15)
ax2.tick_params(pad=15)
ax2.xaxis.tick_bottom()
d = .015
kwargs = dict(transform=ax0.transAxes, color='k', clip_on=False)
ax0.plot((-d,+d),(-d,+d), **kwargs)
ax0.plot((1-d,1+d),(-d,+d), **kwargs)
kwargs.update(transform=ax1.transAxes)
ax1.plot((-d,+d),(1-d,1+d), **kwargs)
ax1.plot((1-d,1+d),(1-d,1+d), **kwargs)
ax1.plot((-d,+d),(-d,+d), **kwargs)
ax1.plot((1-d,1+d),(-d,+d), **kwargs)
kwargs.update(transform=ax2.transAxes)
ax1.plot((-d,+d),(1-d/4,1+d/4), **kwargs)
ax1.plot((1-d,1+d),(1-d/4,1+d/4), **kwargs)
plt.show()
```
which results in I would like to decrease tick labels in the two upper subplots. How to do that ? Thanks. Bonus: 1) how to get rid of the dotted line on y=0 at the basis of the bars? 2) how to get rid of x-trick label between subplot 0 and 1? 3) how to set the back of the plot to transparency? (see the right-bottom broken y-axis line that disappears behind the back of the plot)

Response:
A general approach is to tell matplotlib the desired number of ticks:
```
plt.locator_params(nbins=10)
```
Edit by comments from @Daniel Power: to change for a single axis (e.g. 'x') on an axis, use:
```
ax.locator_params(nbins=10, axis='x')
```


Question: Matplotlib transparent line plots I am plotting two similar trajectories in matplotlib and I'd like to plot each of the lines with partial transparency so that the red (plotted second) doesn't obscure the blue. EDIT: Here's the image with transparent lines.

Response:
Plain and simple:
```
plt.plot(x, y, 'r-', alpha=0.7)
```
(I know I add nothing new, but the straightforward answer should be visible).


Question: Matplotlib imshow - Change default colour normalisation I have consistently had problems with my colour maps when using imshow; some colours seem to just become black. I have finally realised that imshow seems to, by default, normalise the matrix of floating point values I give it. I would have expected an array such as [[0,0.25],[0.5,0.75]] to display the appropriate colours from the map, corresponding to those absolute values but the 0.75 will be interpreted as a 1. In the extreme case, an N x N array of 0.2 (for example), would just produce one big black square, rather than whatever one would expect 0.2 to correspond to in the colour map (perhaps a 20% grey). Is there a way to prevent this behaviour? It is particularly annoying when custom colour maps have many discontinuities; a small change in scale could cause all the colours to completely change.

Response:
Just specify vmin=0, vmax=1. By default, imshow normalizes the data to its min and max. You can control this with either the vmin and vmax arguments or with the norm argument (if you want a non-linear scaling). As a quick example:
```
import matplotlib.pyplot as plt

data = [[0, 0.25], [0.5, 0.75]]

fig, ax = plt.subplots()
im = ax.imshow(data, cmap=plt.get_cmap('hot'), interpolation='nearest',
               vmin=0, vmax=1)
fig.colorbar(im)
plt.show()
```


Question:
Matplotlib axis with two scales shared origin I need two overlay two datasets with different Y-axis scales in Matplotlib. The data contains both positive and negative values. I want the two axes to share one origin, but Matplotlib does not align the two scales by default.
```
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()

ax1.bar(range(6), (2, -2, 1, 0, 0, 0))
ax2.plot(range(6), (0, 2, 8, -2, 0, 0))
plt.show()
```
I suppose it is possible to perform some computation with .get_ylim() and .set_ylim() two align the two scales. Is there an easier solution?

Response:
use the align_yaxis() function:
```
import numpy as np
import matplotlib.pyplot as plt

def align_yaxis(ax1, v1, ax2, v2):
    """adjust ax2 ylimit so that v2 in ax2 is aligned to v1 in ax1"""
    _, y1 = ax1.transData.transform((0, v1))
    _, y2 = ax2.transData.transform((0, v2))
    inv = ax2.transData.inverted()
    _, dy = inv.transform((0, 0)) - inv.transform((0, y1-y2))
    miny, maxy = ax2.get_ylim()
    ax2.set_ylim(miny+dy, maxy+dy)

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()

ax1.bar(range(6), (2, -2, 1, 0, 0, 0))
ax2.plot(range(6), (0, 2, 8, -2, 0, 0))

align_yaxis(ax1, 0, ax2, 0)
plt.show()
```


Question:
limit the number of groups shown in seaborn countplot? Is it possible to show only the top/bottom n groups in asns.countplot()? Using an example from the seaborn website,
```
sns.countplot(y="deck", hue="class", data=titanic, palette="Greens_d");
```
Is there any easy (or even relatively straightforward) way of limiting this plot to just 3 decks (groups) instead of displaying all 7 or is this something that would be better accomplished with an sns.bargraph or just plain matplotlib?

Response:
```
import seaborn as sns
titanic = sns.load_dataset("titanic")
sns.countplot(y="deck", hue="class", data=titanic, palette="Greens_d",
              order=titanic.deck.value_counts().iloc[:3].index)
```


Question: How to display only a left and bottom box border in matplotlib? I'm trying to plot data in matplotlib. I would like to hide the upper and right parts of the box. Does anyone know how to do this? Thanks for your help

Response:
Just set the spines (and/or ticks) to be invisible. E.g.
```
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)

plt.show()
```
If you want to hide the ticks on the top and left as well, just do:
```
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
```


Question:
Manually set color of points in legend I'm making a scatter plot which looks like this: (MWE at bottom of question) As can be seen in the image above the colors of the points in the legend are set to blue automatically by matplotlib. I need to set this points to some other color not present in the colormap (ie: black) so they won't generate confusion with the colors associated with said colormap. I looked around but the matplotlib.legend module does not seem to accept a color keyword. Is there any way to do this? Here's the MWE:
```
import matplotlib.pyplot as plt
import numpy as np

def rand_data():
    return np.random.uniform(low=0., high=1., size=(100,))

# Generate data.
x, y, x2, x3 = [rand_data() for i in range(4)]
# This data defines the markes and labels used.
x1 = np.random.random_integers(7, 9, size=(100,))

# Order all lists so smaller points are on top.
order = np.argsort(-np.array(x2))
# Order x and y.
x_o, y_o = np.take(x, order), np.take(y, order)
# Order list related to markers and labels.
z1 = np.take(x1, order)
# Order list related to sizes.
z2 = np.take(x2, order)
# Order list related to colors.
z3 = np.take(x3, order)

plt.figure()
cm = plt.cm.get_cmap('RdYlBu')

# Scatter plot where each value in z1 has a different marker and label
# assigned.
mrk = {7: ('o', '7'), 8: ('s', '8'), 9: ('D', '9')}
for key, value in mrk.items():

    s1 = (z1 == key)
    plt.scatter(x_o[s1], y_o[s1], marker=value[0], label=value[1],
        s=z2[s1] * 100., c=z3[s1], cmap=cm, lw=0.2)

# Plot colorbar
plt.colorbar()

# Plot legend.
plt.legend(loc="lower left", markerscale=0.7, scatterpoints=1, fontsize=10)

plt.show()
```

Response:
You can obtain the legend handles and change their colors individually. Thanks for the comments of @OrOrg and @Reinderien that led me to update this answer.
```
ax = plt.gca()
leg = ax.get_legend()
leg.legend_handles[0].set_facecolor('red')
leg.legend_handles[0].set_edgecolor('red')

leg.legend_handles[1].set_facecolor('yellow')
leg.legend_handles[1].set_edgecolor('yellow')
```


Question:
Plot a plane and points in 3D simultaneously I m trying to plot simultaneously a plane and some points in 3D with Matplotlib. I have no errors just the point will not appear. I can plot at different times some points and planes but never at same time. The part of the code looks like :
```
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

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

point2 = np.array([10, 50, 50])

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

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

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

# plot the surface
plt3d = plt.figure().gca(projection='3d')
plt3d.plot_surface(xx, yy, z, alpha=0.2)

#and i would like to plot this point :
ax.scatter(point2[0] , point2[1] , point2[2],  color='green')

plt.show()
```

Response:
Just to add to @suever's answer, you there's no reason why you can't create the Axes and then plot both the surface and the scatter points on it. Then there's no need to use ax.hold():
```
# Create the figure
fig = plt.figure()

# Add an axes
ax = fig.add_subplot(111,projection='3d')

# plot the surface
ax.plot_surface(xx, yy, z, alpha=0.2)

# and plot the point
ax.scatter(point2[0] , point2[1] , point2[2],  color='green')
```


Question:
How do I work with images in Bokeh (Python) For example you can plot an image in matplotlib using this code:
```
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img=mpimg.imread('image.png')
plt.imshow(img)
```
Is something like this possible with Bokeh(0.10)?

Response:
You can use the ImageURL glyph (image_url plot method)to load images locally or from the web.
```
from bokeh.plotting import figure, show, output_file

output_file('image.html')

p = figure(x_range=(0,1), y_range=(0,1))
p.image_url(url=['tree.png'], x=0, y=1, w=0.8, h=0.6)
## could also leave out keywords
# p.image_url(['tree.png'], 0, 1, 0.8, h=0.6)
show(p)
```
One gotcha - if you graph only an image (and no other data), you'll have to explicitly set the plot ranges. Here's the docs: http://docs.bokeh.org/en/latest/docs/reference/models/glyphs.html#bokeh.models.glyphs.ImageURL


Question: How to change data points color based on some variable I have 2 variables (x,y) that change with time (t). I want to plot x vs. t and color the ticks based on the value of y. e.g. for highest values of y the tick color is dark green, for lowest value is dark red, and for intermediate values the color will be scaled in between green and red. Can this be done with matplotlib in python?

Response:
This is what matplotlib.pyplot.scatter is for. If no colormap is specified, scatter will use whatever the default colormap is set to. To specify which colormap scatter should use, use the cmap kwarg (e.g. cmap="jet"). As a quick example:
```
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np

# Generate data...
t = np.linspace(0, 2 * np.pi, 20)
x = np.sin(t)
y = np.cos(t)

plt.scatter(t, x, c=y, ec='k')
plt.show()
```
One may specify a custom color map and norm
```py
cmap, norm = mcolors.from_levels_and_colors([0, 2, 5, 6], ['red', 'green', 'blue'])
plt.scatter(x, y, c=t, cmap=cmap, norm=norm)
```


Question:
matplotlib Legend Markers Only Once I often plot a point on a matplotlib plot with:
```
x = 10
y = 100
plot(x, y, "k*", label="Global Optimum")
legend()
```
However, this causes the legend to put a star in the legend twice, such that it looks like:
```
* * Global Optimum
```
when I really want it to look like:
```
*  Global Optimum
```
How do I do this?

Response:
This should work:
```
legend(numpoints=1)
```
BTW, if you add the line
```
legend.numpoints     : 1      # the number of points in the legend line
```
to your matplotlibrc file, then this will be the new default. [See also scatterpoints, depending on your plot.] API: Link to API docs


Question:
Difference between plt.imshow and cv2.imshow? Why is there a difference in the output image when calling the same image using plt.imshow & cv2.imshow()? Here is my code:
```
import cv2
import numpy as np
from matplotlib import pyplot as plt

src=cv2.imread('fruits1.jpg') # Source image

plt.subplot(211),plt.imshow(src),plt.title('image')
plt.xticks([]),plt.yticks([])
plt.show()

cv2.imshow('image',src)
cv2.waitKey(0)
cv2.destroyWindow()
```
Here is the image from plt.imshow: and the second one is the original image: Is there some modification required with the plt.imshow()?

Response: Because OpenCV stores images in BGR order instead of RGB. Try plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) See here for an example.


Question:
Save plot to image file instead of displaying it This displays the figure in a GUI:
```
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.show()
```
But how do I instead save the figure to a file (e.g. foo.png)?

Response:
When using matplotlib.pyplot.savefig, the file format can be specified by the extension:
```
from matplotlib import pyplot as plt

plt.savefig('foo.png')
plt.savefig('foo.pdf')
```
That gives a rasterized or vectorized output respectively. In addition, there is sometimes undesirable whitespace around the image, which can be removed with:
```
plt.savefig('foo.png', bbox_inches='tight')
```
Note that if showing the plot, plt.show() should follow plt.savefig(); otherwise, the file image will be blank.


Question:
Creating graph with date and time in ticklabels with matplotlib I have my data in an array of the following structure,
```py
[[1293606162197, 0, 0],
 [1293605477994, 63, 0],
 [1293605478057, 0, 0],
 [1293605478072, 2735, 1249],
 [1293606162213, 0, 0],
 [1293606162229, 0, 0]]
```
The first column is epoch time (in ms), second is y1 and third is y2. I need a plot with the time on the x-axis, and y1 and y2 on left and right y-axes. I have been scouring through the documentation but couldn't find any way to get my x-axis ticks to display both date and time, like "28/12 16:48", i.e., "date/month hour:min". All the documentation helps me with is to display dates alone, but that is not what I want. It is actually a follow-up to my previous question.

Response:
I hope this helps. I've always had a hard time with matplotlib's dates. Matplotlib requires a float format which is days since epoch. The helper functions num2date and date2num along with python builtin datetime can be used to convert to/from. The formatting business was lifted from this example. You can change an axis on any plot to a date axis using set_major_formatter.
```
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import dates
import datetime

a = np.array([
    [1293605162197, 0, 0],
    [1293605477994, 63, 0],
    [1293605478057, 0, 0],
    [1293605478072, 2735, 1249],
    [1293606162213, 0, 0],
    [1293606162229, 0, 0]])

d = a[:,0]
y1 = a[:,1]
y2 = a[:,2]

# convert epoch to matplotlib float format
s = d/1000
ms = d-1000*s  # not needed?
dts = map(datetime.datetime.fromtimestamp, s)
fds = dates.date2num(dts) # converted

# matplotlib date format object
hfmt = dates.DateFormatter('%m/%d %H:%M')

fig = plt.figure()
ax = fig.add_subplot(111)
ax.vlines(fds, y2, y1)

ax.xaxis.set_major_locator(dates.MinuteLocator())
ax.xaxis.set_major_formatter(hfmt)
ax.set_ylim(bottom = 0)
plt.xticks(rotation='vertical')
plt.subplots_adjust(bottom=.3)
plt.show()
```


Question:
grid zorder seems not to take effect (matplotlib) I am trying to to plot scatter points on a grid using python's matplotlib (1.4.3 but tried on other versions without success too). Everything works except the grid zorder position. I set grid's zorder to be lower that that of scatter but the grid still covers the scatter points. Here is a simple code to reproduce the problem:
```
import numpy as np
from matplotlib import pyplot as plt

# create points
pnts = np.array([[1., 1.], [1., 1.2]])

# create figure
plt.grid(True, linestyle='-', color='r', zorder=1)
plt.scatter(pnts[:,0], pnts[:,1], zorder=2)
plt.ylim([0, 2])
plt.xlim([0, 2])
plt.savefig('testfig.png', dpi=350)
```
I get this: If you zoom in on the dots, you can see the grid is on top, although it has lower zorder: Is this a bug or am I doing something wrong?

Response: In case anyone is still wondering about this years later (like myself), this is a long standing issue (Sept 2015): Axes.grid() not honoring specified "zorder" kwarg Quoting the issue: Axes.grid() is not honoring a provided custom zorder. Instead the grid's zorder seems to be fixed at some miraculous value in between 2.5 and 2.6 (I could not find a key for grid zorder in rcParams). Apparently the only solution so far is to: just add 2.5 to all of your z-orders. There's also an old answer in this question Matplotlib: draw grid lines behind other graph elements but it does not seem to work anymore.


Question: Standalone colorbar I'm rendering some graphics in python with matplotlib, and will include them into a LaTeX paper (using LaTex's nice tabular alignment instead of fiddling with matplotlib's ImageGrid, etc.). I would like to create and save a standalone colorbar with savefig, without needing to use imshow. (the vlim, vmax parameters, as well as the cmap could be provided explicitly) The only way I could find was quite complicated and (from what I understand) draws a hard-coded rectangle onto the canvas: http://matplotlib.org/examples/api/colorbar_only.html Is there an elegant way to create a standalone colorbar with matplotlib?

Response:
You can create some dummy image and then hide it's axe. Draw your colorbar in a customize Axes.
```
import pylab as pl
import numpy as np

a = np.array([[0,1]])
pl.figure(figsize=(9, 1.5))
img = pl.imshow(a, cmap="Blues")
pl.gca().set_visible(False)
cax = pl.axes([0.1, 0.2, 0.8, 0.6])
pl.colorbar(orientation="horizontal", cax=cax)
pl.savefig("colorbar.pdf")
```
the result:


Question: Format of datetime in pyplot axis I am trying to plot some data against a list of datetime objects in the x axis with pyplot. However the dates appear as the standard format, which is %Y-%m-%d %H:%M:%S (way too long). I can circumvent this by creating a list of date strings with strftime and use that instead. I also know that there is some kind of date object intrinsic for pyplot which I could use instead of datetime. Is there a way to tell pyplot in which format to plot the datetimeobjects however? Without having to transform everything to string or another kind of object? Thank you.

Response:
You can use DateFormatter:
```
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(your_dates, your_data)

# format your data to desired format. Here I chose YYYY-MM-DD but you can set it to whatever you want.
import matplotlib.dates as mdates
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))

# rotate and align the tick labels so they look better
fig.autofmt_xdate()
```


Question: How to decouple hatch and edge color in matplotlib? I would like to draw a bar in matplotlib with white as fill color, red as hatch color and black as edge color. However, it looks like the edge color changes also the color of hatch. So, I am not able to decouple the color of edges and hatch. Do you have any suggestion? Thanks.

Response:
Plot bar plot twice:
```
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse, Polygon

fig = plt.figure()
ax1 = fig.add_subplot(111)
# draw hatch
ax1.bar(range(1, 5), range(1, 5), color='none', edgecolor='red', hatch="/", lw=1., zorder = 0)
# draw edge
ax1.bar(range(1, 5), range(1, 5), color='none', edgecolor='k', zorder=1, lw=2.)

ax1.set_xticks([1.5, 2.5, 3.5, 4.5])
plt.show()
```


Question:
matplotlib.pyplot How to name different lines in the same plot? Think about doing this:
```
import matplotlib.pyplot as plt

plt.plot(x_A,y_A,'g--')
plt.plot(x_B,y_B,'r-o')
plt.show()
```
How would you go about giving both lines different names, i.e. like Microsoft Excel would do it?

Response:
```
import matplotlib.pyplot as plt

plt.plot(x_A,y_A,'g--', label="plot A")
plt.plot(x_B,y_B,'r-o', label="plot A")
plt.legend()
plt.show()
```


Question:
python numpy/scipy curve fitting I have some points and I am trying to fit curve for this points. I know that there exist scipy.optimize.curve_fit function, but I do not understand the documentation, i.e. how to use this function. My points:
```py
np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
```
Can anybody explain how to do that?

Response:
I suggest you to start with simple polynomial fit, scipy.optimize.curve_fit tries to fit a function f that you must know to a set of points. This is a simple 3 degree polynomial fit using numpy.polyfit and poly1d, the first performs a least squares polynomial fit and the second calculates the new points:
```
import numpy as np
import matplotlib.pyplot as plt

points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
# get x and y vectors
x = points[:,0]
y = points[:,1]

# calculate polynomial
z = np.polyfit(x, y, 3)
f = np.poly1d(z)

# calculate new x's and y's
x_new = np.linspace(x[0], x[-1], 50)
y_new = f(x_new)

plt.plot(x,y,'o', x_new, y_new)
plt.xlim([x[0]-1, x[-1] + 1 ])
plt.show()
```


Question: How do you determine which backend is being used by matplotlib? Either interactively, such as from within an Ipython session, or from within a script, how can you determine which backend is being used by matplotlib?

Response:
Use the get_backend() function to obtain a string denoting which backend is in use:
```

```python
import matplotlib
```

```python
matplotlib.get_backend()
#Output
#'TkAgg'
#```
```


Question: Shading an area between two points in a matplotlib plot How do you add a shaded area between two points in a matplotlib plot? In the example matplotlib plot below, I manually added the shaded, yellow area using Skitch. I'd like to know how to do this sans-Skitch.

Response:
You can just use the function axvspan. The advantage to this is that the vertical region (or horizontal, in the case of axhspan) will remain shaded regardless of how you pan/zoom the plot. There's a complete example here. See a simple example below:
```
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 20, 500)
y = np.cos(3*x) - 2*np.cos(5*x) + 0.5*np.cos(6*x)

a = 5
b = 15

plt.axvspan(a, b, color='y', alpha=0.5, lw=0)
plt.plot(x, y)
plt.savefig('shade.png', dpi=300)
plt.show()
```
That gives as a result


Question:
Matplotlib - How to remove a specific line or curve I want to remove a specific line in a plot of multiple lines. Bellow is a given example which is not sufficient for me because it removes only the last plotted line and not the line that I want to remove. How can I do that? How can I address a specific line(by name, by number, by reference) throughout the program and delete that line?
```
self.axes.lines.remove(self.axes.lines[0])
```

Response:
Almost all of the plotting functions return a reference to the artist object created ex:
```
ln, = plot(x, y)  # plot actually returns a list of artists, hence the ,
im = imshow(Z)
```
If you have the reference you can remove an artist via the remove (doc) function ex:
```
ln.remove()
im.remove()
```


Question:
Numpy converting array from float to strings I have an array of floats that I have normalised to one (i.e. the largest number in the array is 1), and I wanted to use it as colour indices for a graph. In using matplotlib to use grayscale, this requires using strings between 0 and 1, so I wanted to convert the array of floats to an array of strings. I was attempting to do this by using "astype('str')", but this appears to create some values that are not the same (or even close) to the originals. I notice this because matplotlib complains about finding the number 8 in the array, which is odd as it was normalised to one! In short, I have an array phis, of float64, such that:
```
numpy.where(phis.astype('str').astype('float64') != phis)
```
is non empty. This is puzzling as (hopefully naively) it appears to be a bug in numpy, is there anything that I could have done wrong to cause this? Edit: after investigation this appears to be due to the way the string function handles high precision floats. Using a vectorized toString function (as from robbles answer), this is also the case, however if the lambda function is:
```
lambda x: "%.2f" % x
```
Then the graphing works - curiouser and curiouser. (Obviously the arrays are no longer equal however!)

Response: You seem a bit confused as to how numpy arrays work behind the scenes. Each item in an array must be the same size. The string representation of a float doesn't work this way. For example, repr(1.3) yields '1.3', but repr(1.33) yields '1.3300000000000001'. A accurate string representation of a floating point number produces a variable length string. Because numpy arrays consist of elements that are all the same size, numpy requires you to specify the length of the strings within the array when you're using string arrays. If you use x.astype('str'), it will always convert things to an array of strings of length 1. For example, using x = np.array(1.344566), x.astype('str') yields '1'! You need to be more explict and use the '|Sx' dtype syntax, where x is the length of the string for each element of the array. For example, use x.astype('|S10') to convert the array to strings of length 10. Even better, just avoid using numpy arrays of strings altogether. It's usually a bad idea, and there's no reason I can see from your description of your problem to use them in the first place...


Question: how to set "camera position" for 3d plots using python/matplotlib? I'm learning how to use mplot3d to produce nice plots of 3d data and I'm pretty happy so far. What I am trying to do at the moment is a little animation of a rotating surface. For that purpose, I need to set a camera position for the 3D projection. I guess this must be possible since a surface can be rotated using the mouse when using matplotlib interactively. But how can I do this from a script? I found a lot of transforms in mpl_toolkits.mplot3d.proj3d but I could not find out how to use these for my purpose and I didn't find any example for what I'm trying to do.

Response:
By "camera position," it sounds like you want to adjust the elevation and the azimuth angle that you use to view the 3D plot. You can set this with ax.view_init. I've used the below script to first create the plot, then I determined a good elevation, or elev, from which to view my plot. I then adjusted the azimuth angle, or azim, to vary the full 360deg around my plot, saving the figure at each instance (and noting which azimuth angle as I saved the plot). For a more complicated camera pan, you can adjust both the elevation and angle to achieve the desired effect.
```
from mpl_toolkits.mplot3d import Axes3D
    ax = Axes3D(fig)
    ax.scatter(xx,yy,zz, marker='o', s=20, c="goldenrod", alpha=0.6)
    for ii in xrange(0,360,1):
        ax.view_init(elev=10., azim=ii)
        savefig("movie%d.png" % ii)
```


Question:
sklearn plot confusion matrix with labels I want to plot a confusion matrix to visualize the classifer's performance, but it shows only the numbers of the labels, not the labels themselves:
```
from sklearn.metrics import confusion_matrix
import pylab as pl
y_test=['business', 'business', 'business', 'business', 'business', 'business', 'business', 'business', 'business', 'business', 'business', 'business', 'business', 'business', 'business', 'business', 'business', 'business', 'business', 'business']

pred=array(['health', 'business', 'business', 'business', 'business',
       'business', 'health', 'health', 'business', 'business', 'business',
       'business', 'business', 'business', 'business', 'business',
       'health', 'health', 'business', 'health'],
      dtype='|S8')

cm = confusion_matrix(y_test, pred)
pl.matshow(cm)
pl.title('Confusion matrix of the classifier')
pl.colorbar()
pl.show()
```
How can I add the labels (health, business..etc) to the confusion matrix?

Response:
UPDATE: Check the ConfusionMatrixDisplay OLD ANSWER: I think it's worth mentioning the use of seaborn.heatmap here.
```
import seaborn as sns
import matplotlib.pyplot as plt

ax= plt.subplot()
sns.heatmap(cm, annot=True, fmt='g', ax=ax);  #annot=True to annotate cells, ftm='g' to disable scientific notation

# labels, title and ticks
ax.set_xlabel('Predicted labels');ax.set_ylabel('True labels');
ax.set_title('Confusion Matrix');
ax.xaxis.set_ticklabels(['business', 'health']); ax.yaxis.set_ticklabels(['health', 'business']);
```


Question:
How to add a line of best fit to scatter plot I'm currently working with Pandas and matplotlib to perform some data visualization and I want to add a line of best fit to my scatter plot. Here is my code:
```
import matplotlib
import matplotlib.pyplot as plt
import pandas as panda
import numpy as np

def PCA_scatter(filename):

   matplotlib.style.use('ggplot')

   data = panda.read_csv(filename)
   data_reduced = data[['2005', '2015']]

   data_reduced.plot(kind='scatter', x='2005', y='2015')
   plt.show()

PCA_scatter('file.csv')
```
How do I go about this?

Response:
You can do the whole fit and plot in one fell swoop with the figure-level function seaborn.lmplot, or the axes-level function seaborn.regplot Figure-level vs. axes-level functions seaborn is a high-level API for matplotlib. It's a plotting API, not a stats packages. If the values are required, see How to get the numerical fitting results when plotting a regression in seaborn.
```py
import seaborn as sns

# sample data
penguins = sns.load_dataset('penguins')

# plot 1 with axes level-plot
ax = sns.regplot(data=penguins, x="bill_length_mm", y="bill_depth_mm")

# plot 2 corresponding figure-level plot
g = sns.lmplot(data=penguins, x="bill_length_mm", y="bill_depth_mm")

# plot 3 figure-level plot separated by species
g = sns.lmplot(data=penguins, x="bill_length_mm", y="bill_depth_mm", hue="species")
```
Plot 1 Plot 2 Plot 3


Question:
automatically position text box in plot Is there a way of telling pyplot.text() a location like you can with pyplot.legend()? Something like the legend argument would be excellent:
```
plt.legend(loc="upper left")
```
I am trying to label subplots with different axes using letters (e.g. "A","B"). I figure there's got to be a better way than manually estimating the position.

Response:
Just use annotate and specify axis coordinates. For example, "upper left" would be:
```
plt.annotate('Something', xy=(0.05, 0.95), xycoords='axes fraction')
```
You could also get fancier and specify a constant offset in points:
```
plt.annotate('Something', xy=(0, 1), xytext=(12, -12), va='top'
             xycoords='axes fraction', textcoords='offset points')
```
For more explanation see the examples here and the more detailed examples here.


Question:
Accessing Matplotlib Text Object Label Text Attempting to access the length of a matplotlib axis label with this code:
```
for label in ax.xaxis.get_ticklabels()[1::2]:
        print(len(label))
```
However I am getting an error that the object does not have a length attribute. print(label[2]) also errors out with a similar error.

Response:
Matplotlib's text objects can't be accessed through standard indexing - what you're looking for is the get_text() attribute found in the text object documentation. E.g.
```
for label in ax.xaxis.get_tick_labels()[1::2]:
    print(len(label.get_text()))
```


Question:
Label axes on Seaborn Barplot I'm trying to use my own labels for a Seaborn barplot with the following code:
```py
import pandas as pd
import seaborn as sns

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
fig = sns.barplot(x = 'val', y = 'cat',
                  data = fake,
                  color = 'black')
fig.set_axis_labels('Colors', 'Values')
```
However, I get an error that:
```none
AttributeError: 'AxesSubplot' object has no attribute 'set_axis_labels'
```
Why am I getting this error?

Response:
Seaborn's barplot returns an axis-object (not a figure). This means you can do the following:
```
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
ax = sns.barplot(x = 'val', y = 'cat',
              data = fake,
              color = 'black')
ax.set(xlabel='common xlabel', ylabel='common ylabel')
plt.show()
```


Question: How do I add space between the ticklabels and the axes I've increased the font of my ticklabels successfully, but now they're too close to the axis. I'd like to add a little breathing room between the ticklabels and the axis.

Response: If you don't want to change the spacing globally (by editing your rcParams), and want a cleaner approach, try this: ax.tick_params(axis='both', which='major', pad=15) or for just x axis ax.tick_params(axis='x', which='major', pad=15) or the y axis ax.tick_params(axis='y', which='major', pad=15)