question stringlengths 72 20.5k | response stringlengths 25 15.9k | best_answers_score float64 0.6 0.8 | library_name stringclasses 7
values | question_url stringlengths 61 128 | best_answers_votes int64 1 4.7k | tags listlengths 1 5 | question_length int64 72 20.5k | response_length int64 25 15.9k | tag_count int64 1 5 |
|---|---|---|---|---|---|---|---|---|---|
How do I set the figure title and axes labels font size? I am creating a figure in Matplotlib like this:
```py
from matplotlib import pyplot as plt
fig = plt.figure()
plt.plot(data)
fig.suptitle('test title')
plt.xlabel('xlabel')
plt.ylabel('ylabel')
fig.savefig('test.jpg')
```
I want to specify font sizes for the fi... | Functions dealing with text like label, title, etc. accept parameters same as matplotlib.text.Text. For the font size you can use size/fontsize:
```
from matplotlib import pyplot as plt
fig = plt.figure()
plt.plot(data)
fig.suptitle('test title', fontsize=20)
plt.xlabel('xlabel', fontsize=18)
plt.ylabel('ylabel',... | 0.8 | matplotlib | https://stackoverflow.com/questions/12444716/how-do-i-set-the-figure-title-and-axes-labels-font-size | 1,262 | [
"python",
"matplotlib",
"axis-labels",
"yaxis",
"x-axis"
] | 555 | 784 | 5 |
When to use cla(), clf() or close() for clearing a plot Matplotlib offers these functions:
```py
cla() # Clear axis
clf() # Clear figure
close() # Close a figure window
```
When should I use each function and what exactly does it do? | They all do different things, since matplotlib uses a hierarchical order in which a figure window contains a figure which may consist of many axes. Additionally, there are functions from the pyplot interface and there are methods on the Figure class. I will discuss both cases below. pyplot interface pyplot is a module ... | 0.8 | matplotlib | https://stackoverflow.com/questions/8213522/when-to-use-cla-clf-or-close-for-clearing-a-plot | 960 | [
"python",
"matplotlib",
"plot"
] | 238 | 1,898 | 3 |
What does the argument mean in fig.add_subplot(111)? Sometimes I come across code such as this:
```
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
fig = plt.figure()
fig.add_subplot(111)
plt.scatter(x, y)
plt.show()
```
Which produces: I've been reading the documentation like crazy but I can... | I think this would be best explained by the following picture: To initialize the above, one would type:
```
import matplotlib.pyplot as plt
fig = plt.figure()
fig.add_subplot(221) #top left
fig.add_subplot(222) #top right
fig.add_subplot(223) #bottom left
fig.add_subplot(224) #bottom right
plt.show()
``` | 0.8 | matplotlib | https://stackoverflow.com/questions/3584805/what-does-the-argument-mean-in-fig-add-subplot111 | 638 | [
"python",
"matplotlib",
"subplot",
"figure"
] | 428 | 315 | 4 |
How to change the figure size of a seaborn axes or figure level plot How do I change the size of my image so it's suitable for printing? For example, I'd like to use an A4 paper, whose dimensions are 11.7 inches by 8.27 inches in landscape orientation. | You can also set figure size by passing dictionary to rc parameter with key 'figure.figsize' in seaborn set_theme method (which replaces the set method, deprecated in v0.11.0 (September 2020))
```
import seaborn as sns
sns.set_theme(rc={'figure.figsize':(11.7,8.27)})
```
Other alternative may be to use figure.figsize... | 0.8 | matplotlib | https://stackoverflow.com/questions/31594549/how-to-change-the-figure-size-of-a-seaborn-axes-or-figure-level-plot | 568 | [
"python",
"matplotlib",
"seaborn",
"figsize"
] | 252 | 520 | 4 |
How to remove xticks from a plot I have a semilogx plot and I would like to remove the xticks. I tried:
```
plt.gca().set_xticks([])
plt.xticks([])
ax.set_xticks([])
```
The grid disappears (ok), but small ticks (at the place of the main ticks) remain. How to remove them? | The plt.tick_params method is very useful for stuff like this. This code turns off major and minor ticks and removes the labels from the x-axis. Note that there is also ax.tick_params for matplotlib.axes.Axes objects.
```
from matplotlib import pyplot as plt
plt.plot(range(10))
plt.tick_params(
axis='x', ... | 0.8 | matplotlib | https://stackoverflow.com/questions/12998430/how-to-remove-xticks-from-a-plot | 751 | [
"python",
"matplotlib",
"axis",
"xticks"
] | 273 | 640 | 4 |
Matplotlib different size subplots I need to add two subplots to a figure. One subplot needs to be about three times as wide as the second (same height). I accomplished this using GridSpec and the colspan argument but I would like to do this using figure so I can save to PDF. I can adjust the first figure using the fig... | As of matplotlib 3.6.0, width_ratios and height_ratios can now be passed directly as keyword arguments to plt.subplots and subplot_mosaic, as per What's new in Matplotlib 3.6.0 (Sep 15, 2022). f, (a0, a1) = plt.subplots(1, 2, width_ratios=[3, 1]) f, (a0, a1, a2) = plt.subplots(3, 1, height_ratios=[1, 1, 3]) Another way... | 0.8 | matplotlib | https://stackoverflow.com/questions/10388462/matplotlib-different-size-subplots | 668 | [
"python",
"matplotlib",
"subplot",
"figure",
"matplotlib-gridspec"
] | 402 | 1,062 | 5 |
Display image as grayscale I'm trying to display a grayscale image using matplotlib.pyplot.imshow(). My problem is that the grayscale image is displayed as a colormap. I need it to be grayscale because I want to draw on top of the image with color. I read in the image and convert to grayscale using PIL's Image.open().c... | The following code will load an image from a file image.png and will display it as grayscale.
```
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
fname = 'image.png'
image = Image.open(fname).convert("L")
arr = np.asarray(image)
plt.imshow(arr, cmap='gray', vmin=0, vmax=255)
plt.show()
```
If... | 0.8 | matplotlib | https://stackoverflow.com/questions/3823752/display-image-as-grayscale | 520 | [
"python",
"matplotlib",
"grayscale",
"imshow"
] | 691 | 397 | 4 |
How can I convert an RGB image into grayscale in Python? I'm trying to use matplotlib to read in an RGB image and convert it to grayscale. In matlab I use this:
```
img = rgb2gray(imread('image.png'));
```
In the matplotlib tutorial they don't cover it. They just read in the image
```
import matplotlib.image as mpimg... | How about doing it with Pillow:
```
from PIL import Image
img = Image.open('image.png').convert('L')
img.save('greyscale.png')
```
If an alpha (transparency) channel is present in the input image and should be preserved, use mode LA:
```
img = Image.open('image.png').convert('LA')
```
Using matplotlib and the formula... | 0.8 | matplotlib | https://stackoverflow.com/questions/12201577/how-can-i-convert-an-rgb-image-into-grayscale-in-python | 488 | [
"python",
"matplotlib"
] | 1,140 | 683 | 2 |
Is there a way to detach matplotlib plots so that the computation can continue? After these instructions in the Python interpreter one gets a window with a plot:
```
from matplotlib.pyplot import *
plot([1,2,3])
show()
# other code
```
Unfortunately, I don't know how to continue to interactively explore the figure cre... | Use matplotlib's calls that won't block: Using draw():
```
from matplotlib.pyplot import plot, draw, show
plot([1,2,3])
draw()
print('continue computation')
# at the end call show to ensure window won't close.
show()
```
Using interactive mode:
```
from matplotlib.pyplot import plot, ion, show
ion() # enables intera... | 0.8 | matplotlib | https://stackoverflow.com/questions/458209/is-there-a-way-to-detach-matplotlib-plots-so-that-the-computation-can-continue | 265 | [
"python",
"matplotlib",
"plot"
] | 518 | 486 | 3 |
Rotate label text in seaborn I have a simple factorplot
```
import seaborn as sns
g = sns.factorplot("name", "miss_ratio", "policy", dodge=.2,
linestyles=["none", "none", "none", "none"], data=df[df["level"] == 2])
```
The problem is that the x labels all run together, making them unreadable. How do you rotate th... | I had a problem with the answer by @mwaskorn, namely that
```
g.set_xticklabels(rotation=30)
```
fails, because this also requires the labels. A bit easier than the answer by @Aman is to just add
```
plt.xticks(rotation=30)
``` | 0.8 | matplotlib | https://stackoverflow.com/questions/26540035/rotate-label-text-in-seaborn | 449 | [
"python",
"matplotlib",
"seaborn",
"x-axis"
] | 359 | 229 | 4 |
Set markers for individual points on a line I have used Matplotlib to plot lines on a figure. Now I would now like to set the style, specifically the marker, for individual points on the line. How do I do this? To clarify my question, I want to be able to set the style for individual markers on a line, not every marker... | Specify the keyword args linestyle and/or marker in your call to plot. For example, using a dashed line and blue circle markers:
```
plt.plot(range(10), linestyle='--', marker='o', color='b', label='line with marker')
plt.legend()
```
A shortcut call for the same thing:
```
plt.plot(range(10), '--bo', label='line wit... | 0.8 | matplotlib | https://stackoverflow.com/questions/8409095/set-markers-for-individual-points-on-a-line | 552 | [
"python",
"matplotlib"
] | 334 | 2,157 | 2 |
How to convert a NumPy array to PIL image applying matplotlib colormap I want to take a NumPy 2D array which represents a grayscale image, and convert it to an RGB PIL image while applying some of the matplotlib colormaps. I can get a reasonable PNG output by using the pyplot.figure.figimage command:
```
dpi = 100.0
w... | Quite a busy one-liner, but here it is: First ensure your NumPy array, myarray, is normalised with the max value at 1.0. Apply the colormap directly to myarray. Rescale to the 0-255 range. Convert to integers, using np.uint8(). Use Image.fromarray(). And you're done:
```
from PIL import Image
from matplotlib import cm... | 0.8 | matplotlib | https://stackoverflow.com/questions/10965417/how-to-convert-a-numpy-array-to-pil-image-applying-matplotlib-colormap | 400 | [
"python",
"numpy",
"matplotlib",
"python-imaging-library",
"color-mapping"
] | 777 | 419 | 5 |
Reduce left and right margins in matplotlib plot I'm struggling to deal with my plot margins in matplotlib. I've used the code below to produce my chart:
```
plt.imshow(g)
c = plt.colorbar()
c.set_label("Number of Slabs")
plt.savefig("OutputToUse.png")
```
However, I get an output figure with lots of white space on ei... | One way to automatically do this is the bbox_inches='tight' kwarg to plt.savefig. E.g.
```
import matplotlib.pyplot as plt
import numpy as np
data = np.arange(3000).reshape((100,30))
plt.imshow(data)
plt.savefig('test.png', bbox_inches='tight')
```
Another way is to use fig.tight_layout()
```
import matplotlib.pyplot... | 0.8 | matplotlib | https://stackoverflow.com/questions/4042192/reduce-left-and-right-margins-in-matplotlib-plot | 392 | [
"python",
"matplotlib"
] | 447 | 562 | 2 |
Getting individual colors from a color map in matplotlib If you have a Colormap cmap, for example:
```
cmap = matplotlib.cm.get_cmap('Spectral')
```
How can you get a particular colour out of it between 0 and 1, where 0 is the first colour in the map and 1 is the last colour in the map? Ideally, I would be able to get... | You can do this with the code below, and the code in your question was actually very close to what you needed, all you have to do is call the cmap object you have.
```
import matplotlib
cmap = matplotlib.cm.get_cmap('Spectral')
rgba = cmap(0.5)
print(rgba) # (0.99807766255210428, 0.99923106502084169, 0.7460207763840... | 0.8 | matplotlib | https://stackoverflow.com/questions/25408393/getting-individual-colors-from-a-color-map-in-matplotlib | 415 | [
"python",
"matplotlib",
"colors"
] | 441 | 1,373 | 3 |
How to do a scatter plot with empty circles in Python? In Python, with Matplotlib, how can a scatter plot with empty circles be plotted? The goal is to draw empty circles around some of the colored disks already plotted by scatter(), so as to highlight them, ideally without having to redraw the colored circles. I tried... | From the documentation for scatter:
```
Optional kwargs control the Collection properties; in particular:
edgecolors:
The string ‘none’ to plot faces with no outlines
facecolors:
The string ‘none’ to plot unfilled outlines
```
Try the following:
```
import matplotlib.pyplot as plt
import num... | 0.8 | matplotlib | https://stackoverflow.com/questions/4143502/how-to-do-a-scatter-plot-with-empty-circles-in-python | 408 | [
"python",
"matplotlib",
"geometry",
"scatter-plot",
"scatter"
] | 350 | 550 | 5 |
How to plot in multiple subplots I am a little confused about how this code works:
```
fig, axes = plt.subplots(nrows=2, ncols=2)
plt.show()
```
How does the fig, axes work in this case? What does it do? Also why wouldn't this work to do the same thing:
```
fig = plt.figure()
axes = fig.subplots(nrows=2, ncols=2)
``` | There are several ways to do it. The subplots method creates the figure along with the subplots that are then stored in the ax array. For example:
```
import matplotlib.pyplot as plt
x = range(10)
y = range(10)
fig, ax = plt.subplots(nrows=2, ncols=2)
for row in ax:
for col in row:
col.plot(x, y)
plt.s... | 0.8 | matplotlib | https://stackoverflow.com/questions/31726643/how-to-plot-in-multiple-subplots | 343 | [
"python",
"pandas",
"matplotlib",
"seaborn",
"subplot"
] | 320 | 664 | 5 |
How to set xlim and ylim for a subplot [duplicate] This question already has answers here: How to set the subplot axis range (6 answers) Closed 10 years ago. I would like to limit the X and Y axis in matplotlib for a specific subplot. The subplot figure itself doesn't have any axis property. I want for example to chang... | You should use the object-oriented interface to matplotlib, rather than the state machine interface. Almost all of the plt.* function are thin wrappers that basically do gca().*. plt.subplot returns an axes object. Once you have a reference to the axes object you can plot directly to it, change its limits, etc.
```
im... | 0.8 | matplotlib | https://stackoverflow.com/questions/15858192/how-to-set-xlim-and-ylim-for-a-subplot | 370 | [
"python",
"matplotlib",
"plot",
"subplot"
] | 556 | 957 | 4 |
Date ticks and rotation [duplicate] This question already has answers here: Rotate axis tick labels (13 answers) Closed 2 years ago. I am having an issue trying to get my date ticks rotated in matplotlib. A small sample program is below. If I try to rotate the ticks at the end, the ticks do not get rotated. If I try to... | If you prefer a non-object-oriented approach, move plt.xticks(rotation=70) to right before the two avail_plot calls, eg
```
plt.xticks(rotation=70)
avail_plot(axs[0], dates, s1, 'testing', 'green')
avail_plot(axs[1], dates, s1, 'testing2', 'red')
```
This sets the rotation property before setting up the labels. Since ... | 0.8 | matplotlib | https://stackoverflow.com/questions/11264521/date-ticks-and-rotation | 319 | [
"python",
"matplotlib",
"xticks"
] | 1,492 | 805 | 3 |
Format y axis as percent I have an existing plot that was created with pandas like this:
```
df['myvar'].plot(kind='bar')
```
The y axis is format as float and I want to change the y axis to percentages. All of the solutions I found use ax.xyz syntax and I can only place code below the line above that creates the plot... | This is a few months late, but I have created PR#6251 with matplotlib to add a new PercentFormatter class. With this class you just need one line to reformat your axis (two if you count the import of matplotlib.ticker):
```
import ...
import matplotlib.ticker as mtick
ax = df['myvar'].plot(kind='bar')
ax.yaxis.set_ma... | 0.8 | matplotlib | https://stackoverflow.com/questions/31357611/format-y-axis-as-percent | 376 | [
"python",
"pandas",
"matplotlib",
"plot"
] | 947 | 963 | 4 |
reducing number of plot ticks I have too many ticks on my graph and they are running into each other. How can I reduce the number of ticks? For example, I have ticks:
```
1E-6, 1E-5, 1E-4, ... 1E6, 1E7
```
And I only want:
```
1E-5, 1E-3, ... 1E5, 1E7
```
I've tried playing with the LogLocator, but I haven't been abl... | Alternatively, if you want to simply set the number of ticks while allowing matplotlib to position them (currently only with MaxNLocator), there is pyplot.locator_params,
```
pyplot.locator_params(nbins=4)
```
You can specify specific axis in this method as mentioned below, default is both:
```
# To specify the numbe... | 0.8 | matplotlib | https://stackoverflow.com/questions/6682784/reducing-number-of-plot-ticks | 368 | [
"python",
"matplotlib",
"xticks",
"yticks"
] | 341 | 444 | 4 |
How to plot multiple dataframes in subplots I have a few Pandas DataFrames sharing the same value scale, but having different columns and indices. When invoking df.plot(), I get separate plot images. what I really want is to have them all in the same plot as subplots, but I'm unfortunately failing to come up with a sol... | You can manually create the subplots with matplotlib, and then plot the dataframes on a specific subplot using the ax keyword. For example for 4 subplots (2x2):
```
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=2, ncols=2)
df1.plot(ax=axes[0,0])
df2.plot(ax=axes[0,1])
...
```
Here axes is an array w... | 0.8 | matplotlib | https://stackoverflow.com/questions/22483588/how-to-plot-multiple-dataframes-in-subplots | 414 | [
"python",
"pandas",
"matplotlib",
"seaborn",
"subplot"
] | 371 | 483 | 5 |
How do I equalize the scales of the x-axis and y-axis? How do I create a plot where the scales of x-axis and y-axis are the same? This equal ratio should be maintained even if I change the window size. Currently, my graph scales together with the window size. I tried:
```
plt.xlim(-3, 3)
plt.ylim(-3, 3)
plt.axis('equa... | Use Axes.set_aspect in the following manner:
```
from matplotlib import pyplot as plt
plt.plot(range(5))
plt.xlim(-3, 3)
plt.ylim(-3, 3)
ax = plt.gca()
ax.set_aspect('equal', adjustable='box')
plt.draw()
``` | 0.8 | matplotlib | https://stackoverflow.com/questions/17990845/how-do-i-equalize-the-scales-of-the-x-axis-and-y-axis | 323 | [
"python",
"matplotlib",
"axis",
"aspect-ratio"
] | 327 | 208 | 4 |
Set Colorbar Range I have the following code:
```py
import matplotlib.pyplot as plt
cdict = {
'red' : ( (0.0, 0.25, .25), (0.02, .59, .59), (1., 1., 1.)),
'green': ( (0.0, 0.0, 0.0), (0.02, .45, .45), (1., .97, .97)),
'blue' : ( (0.0, 1.0, 1.0), (0.02, .75, .75), (1., 0.45, 0.45))
}
cm = m.colors.LinearSe... | Using vmin and vmax forces the range for the colors. Here's an example:
```
import matplotlib as m
import matplotlib.pyplot as plt
import numpy as np
cdict = {
'red' : ( (0.0, 0.25, .25), (0.02, .59, .59), (1., 1., 1.)),
'green': ( (0.0, 0.0, 0.0), (0.02, .45, .45), (1., .97, .97)),
'blue' : ( (0.0, 1.0, 1.... | 0.8 | matplotlib | https://stackoverflow.com/questions/3373256/set-colorbar-range | 242 | [
"python",
"matplotlib",
"graph",
"colorbar",
"colormap"
] | 1,482 | 852 | 5 |
How to put individual tags for a matplotlib scatter plot? I am trying to do a scatter plot in matplotlib and I couldn't find a way to add tags to the points. For example:
```
scatter1=plt.scatter(data1["x"], data1["y"], marker="o",
c="blue",
facecolors="white",
... | Perhaps use plt.annotate:
```
import numpy as np
import matplotlib.pyplot as plt
N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]
plt.subplots_adjust(bottom = 0.1)
plt.scatter(
data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
cmap=plt.get_cmap('Sp... | 0.8 | matplotlib | https://stackoverflow.com/questions/5147112/how-to-put-individual-tags-for-a-matplotlib-scatter-plot | 384 | [
"python",
"matplotlib"
] | 448 | 676 | 2 |
Plotting time on the independent axis I have an array of timestamps in the format (HH:MM:SS.mmmmmm) and another array of floating point numbers, each corresponding to a value in the timestamp array. Can I plot time on the x axis and the numbers on the y-axis using Matplotlib? I was trying to, but somehow it was only ac... | Update: This answer is outdated since matplotlib version 3.5. The plot function now handles datetime data directly. See https://matplotlib.org/3.5.1/api/_as_gen/matplotlib.pyplot.plot_date.html The use of plot_date is discouraged. This method exists for historic reasons and may be deprecated in the future. datetime-lik... | 0.8 | matplotlib | https://stackoverflow.com/questions/1574088/plotting-time-on-the-independent-axis | 226 | [
"python",
"matplotlib",
"timestamp",
"x-axis"
] | 423 | 1,048 | 4 |
How do I tell matplotlib that I am done with a plot? The following code plots to two PostScript (.ps) files, but the second one contains both lines.
```
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
plt.subplot(111)
x = [1,10]
y = [30, 1000]
plt.loglog(x, y, basex=10, basey=10, ls="... | There is a clear figure command, and it should do it for you:
```
plt.clf()
```
If you have multiple subplots in the same figure
```
plt.cla()
```
clears the current axes. | 0.8 | matplotlib | https://stackoverflow.com/questions/741877/how-do-i-tell-matplotlib-that-i-am-done-with-a-plot | 227 | [
"python",
"matplotlib",
"plot"
] | 532 | 173 | 3 |
How do I create a second (new) plot, then later plot on the old one? I want to plot data, then create a new figure and plot data2, and finally come back to the original plot and plot data3, kinda like this:
```
import numpy as np
import matplotlib as plt
x = arange(5)
y = np.exp(5)
plt.figure()
plt.plot(x, y)
z = np... | If you find yourself doing things like this regularly it may be worth investigating the object-oriented interface to matplotlib. In your case:
```
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(5)
y = np.exp(x)
fig1, ax1 = plt.subplots()
ax1.plot(x, y)
ax1.set_title("Axis 1 title")
ax1.set_xlabel("X... | 0.8 | matplotlib | https://stackoverflow.com/questions/6916978/how-do-i-create-a-second-new-plot-then-later-plot-on-the-old-one | 197 | [
"python",
"matplotlib",
"plot",
"figure"
] | 593 | 672 | 4 |
How to plot a high resolution graph I've used matplotlib for plotting some experimental results (discussed it in here: Looping over files and plotting. However, saving the picture by clicking right to the image gives very bad quality / low resolution images.
```
from glob import glob
import numpy as np
import matplotl... | You can use savefig() to export to an image file:
```
plt.savefig('filename.png')
```
In addition, you can specify the dpi argument to some scalar value (default is 100). For example:
```
plt.savefig('filename.png', dpi=300)
``` | 0.8 | matplotlib | https://stackoverflow.com/questions/39870642/how-to-plot-a-high-resolution-graph | 303 | [
"python",
"matplotlib"
] | 1,212 | 230 | 2 |
How to display an image I tried to use IPython.display with the following code:
```
from IPython.display import display, Image
display(Image(filename='MyImage.png'))
```
I also tried to use matplotlib with the following code:
```
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
plt.imshow(mpimg.imread... | If you are using matplotlib and want to show the image in your interactive notebook, try the following:
```
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img = mpimg.imread('your_image.png')
imgplot = plt.imshow(img)
plt.show()
``` | 0.8 | matplotlib | https://stackoverflow.com/questions/35286540/how-to-display-an-image | 388 | [
"python",
"opencv",
"matplotlib",
"imshow"
] | 404 | 270 | 4 |
Plotting a list of (x, y) coordinates I have a list of pairs (a, b) that I would like to plot with matplotlib in python as actual x-y coordinates. Currently, it is making two plots, where the index of the list gives the x-coordinate, and the first plot's y values are the as in the pairs and the second plot's y values a... | Given li in the question:
```
li = list(zip(range(1, 14), range(14, 27)))
```
To unpack the data from pairs into lists use zip:
```
x, y = zip(*li)
x → (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)
y → (14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26)
```
The one-liner uses the unpacking operator (*), to unpack the... | 0.8 | matplotlib | https://stackoverflow.com/questions/21519203/plotting-a-list-of-x-y-coordinates | 280 | [
"python",
"list",
"matplotlib",
"plot",
"coordinates"
] | 1,316 | 450 | 5 |
Plt.show shows full graph but savefig is cropping the image My code is succesfully saving images to file, but it is cropping important details from the right hand side. Answers exist for fixing this problem when it arises for plt.show, but it is the savefig command that is incorrectly producing the graph in this exampl... | You may try
```
plt.savefig('X:/' + newName + '.png', bbox_inches='tight')
```
Or you may define figure size like
```
fig = plt.figure(figsize=(9, 11))
...
plt.savefig(filename, bbox_inches = 'tight')
``` | 0.8 | matplotlib | https://stackoverflow.com/questions/37427362/plt-show-shows-full-graph-but-savefig-is-cropping-the-image | 351 | [
"python",
"matplotlib"
] | 849 | 206 | 2 |
How to rotate x-axis tick labels in a pandas plot With the following code:
```
import matplotlib
matplotlib.style.use('ggplot')
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({ 'celltype':["foo","bar","qux","woz"], 's1':[5,9,1,7], 's2':[12,90,13,87]})
df = df[["celltype","s1","s2"]]
df.set_inde... | Pass param rot=0 to rotate the xticklabels:
```
import matplotlib
matplotlib.style.use('ggplot')
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({ 'celltype':["foo","bar","qux","woz"], 's1':[5,9,1,7], 's2':[12,90,13,87]})
df = df[["celltype","s1","s2"]]
df.set_index(["celltype"],inplace=True)
df... | 0.8 | matplotlib | https://stackoverflow.com/questions/32244019/how-to-rotate-x-axis-tick-labels-in-a-pandas-plot | 329 | [
"python",
"pandas",
"matplotlib"
] | 559 | 398 | 3 |
Remove or adapt border of frame of legend using matplotlib When plotting a plot using matplotlib: How to remove the box of the legend? How to change the color of the border of the legend box? How to remove only the border of the box of the legend? | When plotting a plot using matplotlib: How to remove the box of the legend?
```
plt.legend(frameon=False)
```
How to change the color of the border of the legend box?
```
leg = plt.legend()
leg.get_frame().set_edgecolor('b')
```
How to remove only the border of the box of the legend?
```
leg = plt.legend()
leg.get_f... | 0.8 | matplotlib | https://stackoverflow.com/questions/25540259/remove-or-adapt-border-of-frame-of-legend-using-matplotlib | 327 | [
"python",
"matplotlib"
] | 247 | 521 | 2 |
How to pick a new color for each plotted line within a figure I'd like to NOT specify a color for each plotted line, and have each line get a distinct color. But if I run:
```
from matplotlib import pyplot as plt
for i in range(20):
plt.plot([0, 1], [i, i])
plt.show()
```
then I get this output: If you look at th... | I usually use the second one of these:
```py
from matplotlib.pyplot import cm
import numpy as np
#variable n below should be number of curves to plot
#version 1:
color = cm.rainbow(np.linspace(0, 1, n))
for i, c in enumerate(color):
plt.plot(x, y, c=c)
#or version 2:
color = iter(cm.rainbow(np.linspace(0, 1, n... | 0.8 | matplotlib | https://stackoverflow.com/questions/4971269/how-to-pick-a-new-color-for-each-plotted-line-within-a-figure | 223 | [
"python",
"matplotlib",
"colormap"
] | 610 | 402 | 3 |
How to share x axes of two subplots after they have been created I'm trying to share two subplots axes, but I need to share the x axis after the figure was created. E.g. I create this figure:
```py
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(1000)/100.
x = np.sin(2*np.pi*10*t)
y = np.cos(2*np.pi*... | The usual way to share axes is to create the shared properties at creation. Either
```
fig=plt.figure()
ax1 = plt.subplot(211)
ax2 = plt.subplot(212, sharex = ax1)
```
or
```
fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True)
```
Sharing the axes after they have been created should therefore not be necessary. Howev... | 0.8 | matplotlib | https://stackoverflow.com/questions/42973223/how-to-share-x-axes-of-two-subplots-after-they-have-been-created | 265 | [
"python",
"matplotlib",
"axis"
] | 717 | 1,176 | 3 |
How to connect scatterplot points with line using matplotlib I have two lists, dates and values. I want to plot them using matplotlib. The following creates a scatter plot of my data.
```py
import matplotlib.pyplot as plt
plt.scatter(dates,values)
plt.show()
```
plt.plot(dates, values) creates a line graph. But what ... | I think @Evert has the right answer:
```
plt.scatter(dates,values)
plt.plot(dates, values)
plt.show()
```
Which is pretty much the same as
```
plt.plot(dates, values, '-o')
plt.show()
```
You can replace -o with another suitable format string as described in the documentation. You can also split the choices of line a... | 0.8 | matplotlib | https://stackoverflow.com/questions/20130227/how-to-connect-scatterplot-points-with-line-using-matplotlib | 224 | [
"python",
"matplotlib",
"scatter-plot"
] | 580 | 388 | 3 |
How to plot multiple functions on the same figure How can I plot the following 3 functions (i.e. sin, cos and the addition), on the domain t, in the same figure?
```py
import numpy as np
import matplotlib.pyplot as plt
t = np.linspace(0, 2*np.pi, 400)
a = np.sin(t)
b = np.cos(t)
c = a + b
``` | To plot multiple graphs on the same figure you will have to do:
```
from numpy import *
import math
import matplotlib.pyplot as plt
t = linspace(0, 2*math.pi, 400)
a = sin(t)
b = cos(t)
c = a + b
plt.plot(t, a, 'r') # plotting t, a separately
plt.plot(t, b, 'b') # plotting t, b separately
plt.plot(t, c, 'g') # plo... | 0.8 | matplotlib | https://stackoverflow.com/questions/22276066/how-to-plot-multiple-functions-on-the-same-figure | 263 | [
"python",
"function",
"matplotlib",
"plot",
"graph"
] | 296 | 357 | 5 |
Moving x-axis to the top of a plot in matplotlib Based on this question about heatmaps in matplotlib, I wanted to move the x-axis titles to the top of the plot.
```
import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random.rand(4,4)
fig, ax = plt.subplot... | Use
```
ax.xaxis.tick_top()
```
to place the tick marks at the top of the image. The command
```
ax.set_xlabel('X LABEL')
ax.xaxis.set_label_position('top')
```
affects the label, not the tick marks.
```
import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
dat... | 0.8 | matplotlib | https://stackoverflow.com/questions/14406214/moving-x-axis-to-the-top-of-a-plot-in-matplotlib | 242 | [
"python",
"matplotlib",
"plot",
"visualization"
] | 910 | 770 | 4 |
Prevent scientific notation I have the following code:
```
plt.plot(range(2003,2012,1),range(200300,201200,100))
# several solutions from other questions have not worked, including
# plt.ticklabel_format(style='sci', axis='x', scilimits=(-1000000,1000000))
# ax.get_xaxis().get_major_formatter().set_useOffset(False)
pl... | In your case, you're actually wanting to disable the offset. Using scientific notation is a separate setting from showing things in terms of an offset value. However, ax.ticklabel_format(useOffset=False) should have worked (though you've listed it as one of the things that didn't). For example:
```
fig, ax = plt.subpl... | 0.8 | matplotlib | https://stackoverflow.com/questions/28371674/prevent-scientific-notation | 262 | [
"python",
"matplotlib",
"plot",
"scientific-notation",
"xticks"
] | 586 | 1,586 | 5 |
How to maximize a plt.show() window Just for curiosity I would like to know how to do this in the code below. I have been searching for an answer but is useless.
```
import numpy as np
import matplotlib.pyplot as plt
data=np.random.exponential(scale=180, size=10000)
print ('el valor medio de la distribucion exponencia... | I am on a Windows (WIN7), running Python 2.7.5 & Matplotlib 1.3.1. I was able to maximize Figure windows for TkAgg, QT4Agg, and wxAgg using the following lines:
```py
from matplotlib import pyplot as plt
### for 'TkAgg' backend
plt.figure(1)
plt.switch_backend('TkAgg') #TkAgg (instead Qt4Agg)
print '#1 Backend:',plt.... | 0.8 | matplotlib | https://stackoverflow.com/questions/12439588/how-to-maximize-a-plt-show-window | 212 | [
"python",
"matplotlib"
] | 562 | 1,303 | 2 |
How to create major and minor gridlines with different linestyles I am currently using matplotlib.pyplot to create graphs and would like to have the major gridlines solid and black and the minor ones either greyed or dashed. In the grid properties, which=both/major/mine, and then color and linestyle are defined simply ... | Actually, it is as simple as setting major and minor separately:
```
```python
plot([23, 456, 676, 89, 906, 34, 2345])
#Output
#[<matplotlib.lines.Line2D at 0x6112f90>]
```
```python
yscale('log')
```
```python
grid(visible=True, which='major', color='b', linestyle='-')
```
```python
grid(visible=True, which='mino... | 0.8 | matplotlib | https://stackoverflow.com/questions/9127434/how-to-create-major-and-minor-gridlines-with-different-linestyles | 230 | [
"python",
"matplotlib",
"gridlines"
] | 552 | 578 | 3 |
Adding an arbitrary line to a matplotlib plot in ipython notebook I'm rather new to both python/matplotlib and using it through the ipython notebook. I'm trying to add some annotation lines to an existing graph and I can't figure out how to render the lines on a graph. So, for example, if I plot the following:
```
imp... | You can directly plot the lines you want by feeding the plot command with the corresponding data (boundaries of the segments): plot([x1, x2], [y1, y2], color='k', linestyle='-', linewidth=2) (of course you can choose the color, line width, line style, etc.) From your example:
```
import numpy as np
import matplotlib.p... | 0.8 | matplotlib | https://stackoverflow.com/questions/12864294/adding-an-arbitrary-line-to-a-matplotlib-plot-in-ipython-notebook | 231 | [
"matplotlib",
"ipython"
] | 791 | 633 | 2 |
How to display multiple images in one figure [duplicate] This question already has answers here: Multiple figures in a single window (7 answers) Closed 7 years ago. I am trying to display 20 random images on a single Figure. The images are indeed displayed, but they are overlaid. I am using:
```
import numpy as np
imp... | Here is my approach that you may try:
```
import numpy as np
import matplotlib.pyplot as plt
w = 10
h = 10
fig = plt.figure(figsize=(8, 8))
columns = 4
rows = 5
for i in range(1, columns*rows +1):
img = np.random.randint(10, size=(h,w))
fig.add_subplot(rows, columns, i)
plt.imshow(img)
plt.show()
```
The ... | 0.8 | matplotlib | https://stackoverflow.com/questions/46615554/how-to-display-multiple-images-in-one-figure | 332 | [
"python",
"matplotlib",
"imshow"
] | 888 | 3,944 | 3 |
Can Pandas plot a histogram of dates? I've taken my Series and coerced it to a datetime column of dtype=datetime64[ns] (though only need day resolution...not sure how to change).
```
import pandas as pd
df = pd.read_csv('somefile.csv')
column = df['date']
column = pd.to_datetime(column, coerce=True)
```
but plotting d... | Given this df:
```
date
0 2001-08-10
1 2002-08-31
2 2003-08-29
3 2006-06-21
4 2002-03-27
5 2003-07-14
6 2004-06-15
7 2003-08-14
8 2003-07-29
```
and, if it's not already the case:
```
df["date"] = df["date"].astype("datetime64")
```
To show the count of dates by month:
```
df.groupby(df["date"].dt.month).count().plo... | 0.8 | matplotlib | https://stackoverflow.com/questions/27365467/can-pandas-plot-a-histogram-of-dates | 232 | [
"python",
"pandas",
"matplotlib",
"time-series"
] | 599 | 616 | 4 |
Pandas plot doesn't show When using this in a script (not IPython), nothing happens, i.e. the plot window doesn't appear :
```
import numpy as np
import pandas as pd
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts.plot()
```
Even when adding time.sleep(5), there is still nothing... | Once you have made your plot, you need to tell matplotlib to show it. The usual way to do things is to import matplotlib.pyplot and call show from there:
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts.pl... | 0.8 | matplotlib | https://stackoverflow.com/questions/34347145/pandas-plot-doesnt-show | 241 | [
"python",
"pandas",
"matplotlib"
] | 396 | 1,456 | 3 |
Matplotlib figure facecolor (background color) Can someone please explain why the code below does not work when setting the facecolor of the figure?
```
import matplotlib.pyplot as plt
# create figure instance
fig1 = plt.figure(1)
fig1.set_figheight(11)
fig1.set_figwidth(8.5)
rect = fig1.patch
rect.set_facecolor('re... | It's because savefig overrides the facecolor for the background of the figure. (This is deliberate, actually... The assumption is that you'd probably want to control the background color of the saved figure with the facecolor kwarg to savefig. It's a confusing and inconsistent default, though!) The easiest workaround i... | 0.8 | matplotlib | https://stackoverflow.com/questions/4804005/matplotlib-figure-facecolor-background-color | 197 | [
"python",
"matplotlib"
] | 993 | 566 | 2 |
What is the difference between 'log' and 'symlog'? In matplotlib, I can set the axis scaling using either pyplot.xscale() or Axes.set_xscale(). Both functions accept three different scales: 'linear' | 'log' | 'symlog'. What is the difference between 'log' and 'symlog'? In a simple test I did, they both looked exactly t... | I finally found some time to do some experiments in order to understand the difference between them. Here's what I discovered: log only allows positive values, and lets you choose how to handle negative ones (mask or clip). symlog means symmetrical log, and allows positive and negative values. symlog allows to set a ra... | 0.8 | matplotlib | https://stackoverflow.com/questions/3305865/what-is-the-difference-between-log-and-symlog | 245 | [
"python",
"matplotlib",
"scale",
"logarithm"
] | 598 | 1,806 | 4 |
matplotlib colorbar for scatter I'm working with data that has the data has 3 plotting parameters: x,y,c. How do you create a custom color value for a scatter plot? Extending this example I'm trying to do:
```
import matplotlib
import matplotlib.pyplot as plt
cm = matplotlib.cm.get_cmap('RdYlBu')
colors=[cm(1.*i/20) f... | From the matplotlib docs on scatter 1: cmap is only used if c is an array of floats So colorlist needs to be a list of floats rather than a list of tuples as you have it now. plt.colorbar() wants a mappable object, like the CircleCollection that plt.scatter() returns. vmin and vmax can then control the limits of your c... | 0.8 | matplotlib | https://stackoverflow.com/questions/6063876/matplotlib-colorbar-for-scatter | 264 | [
"python",
"colors",
"matplotlib"
] | 604 | 598 | 3 |
Plot a bar using matplotlib using a dictionary Is there any way to plot a bar plot using matplotlib using data directly from a dict? My dict looks like this:
```
D = {u'Label1':26, u'Label2': 17, u'Label3':30}
```
I was expecting
```
fig = plt.figure(figsize=(5.5,3),dpi=300)
ax = fig.add_subplot(111)
bar = ax.bar(D,r... | You can do it in two lines by first plotting the bar chart and then setting the appropriate ticks:
```
import matplotlib.pyplot as plt
D = {u'Label1':26, u'Label2': 17, u'Label3':30}
plt.bar(range(len(D)), list(D.values()), align='center')
plt.xticks(range(len(D)), list(D.keys()))
# # for python 2.x:
# plt.bar(range... | 0.8 | matplotlib | https://stackoverflow.com/questions/16010869/plot-a-bar-using-matplotlib-using-a-dictionary | 208 | [
"python",
"matplotlib",
"plot"
] | 1,441 | 615 | 3 |
OpenCV giving wrong color to colored images on loading I'm loading in a color image in Python OpenCV and plotting the same. However, the image I get has it's colors all mixed up. Here is the code:
```
import cv2
import numpy as np
from numpy import array, arange, uint8
from matplotlib import pyplot as plt
img = cv2... | OpenCV uses BGR as its default colour order for images, matplotlib uses RGB. When you display an image loaded with OpenCv in matplotlib the channels will be back to front. The easiest way of fixing this is to use OpenCV to explicitly convert it back to RGB, much like you do when creating the greyscale image.
```
RGB_i... | 0.8 | matplotlib | https://stackoverflow.com/questions/39316447/opencv-giving-wrong-color-to-colored-images-on-loading | 258 | [
"python",
"opencv",
"matplotlib",
"colors",
"rgb"
] | 725 | 397 | 5 |
plot with custom text for x axis points I am drawing a plot using matplotlib and python like the sample code below.
```
x = array([0,1,2,3])
y = array([20,21,22,23])
plot(x,y)
show()
```
As it is the code above on the x axis I will see drawn values 0.0, 0.5, 1.0, 1.5 i.e. the same values of my reference x values. Is t... | You can manually set xticks (and yticks) using pyplot.xticks:
```
import matplotlib.pyplot as plt
import numpy as np
x = np.array([0,1,2,3])
y = np.array([20,21,22,23])
my_xticks = ['John','Arnold','Mavis','Matt']
plt.xticks(x, my_xticks)
plt.plot(x, y)
plt.show()
``` | 0.8 | matplotlib | https://stackoverflow.com/questions/3100985/plot-with-custom-text-for-x-axis-points | 260 | [
"python",
"matplotlib"
] | 677 | 270 | 2 |
Scatter plot and Color mapping in Python I have a range of points x and y stored in numpy arrays. Those represent x(t) and y(t) where t=0...T-1 I am plotting a scatter plot using
```
import matplotlib.pyplot as plt
plt.scatter(x,y)
plt.show()
```
I would like to have a colormap representing the time (therefore colori... | Here is an example
```
import numpy as np
import matplotlib.pyplot as plt
x = np.random.rand(100)
y = np.random.rand(100)
t = np.arange(100)
plt.scatter(x, y, c=t)
plt.show()
```
Here you are setting the color based on the index, t, which is just an array of [1, 2, ..., 100]. Perhaps an easier-to-understand example ... | 0.8 | matplotlib | https://stackoverflow.com/questions/17682216/scatter-plot-and-color-mapping-in-python | 241 | [
"python",
"matplotlib"
] | 411 | 1,938 | 2 |
Change figure window title in pylab How can I set a figure window's title in pylab/python?
```
fig = figure(9) # 9 is now the title of the window
fig.set_title("Test") #doesn't work
fig.title = "Test" #doesn't work
``` | If you want to actually change the window you can do:
```
fig = pylab.gcf()
fig.canvas.manager.set_window_title('Test')
``` | 0.8 | matplotlib | https://stackoverflow.com/questions/5812960/change-figure-window-title-in-pylab | 185 | [
"python",
"matplotlib"
] | 219 | 124 | 2 |
Defining the midpoint of a colormap in matplotlib I want to set the middle point of a colormap, i.e., my data goes from -5 to 10 and I want zero to be the middle point. I think the way to do it is by subclassing normalize and using the norm, but I didn't find any example and it is not clear to me, what exactly have I t... | I know this is late to the game, but I just went through this process and came up with a solution that perhaps less robust than subclassing normalize, but much simpler. I thought it'd be good to share it here for posterity. The function
```
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from mpl_... | 0.8 | matplotlib | https://stackoverflow.com/questions/7404116/defining-the-midpoint-of-a-colormap-in-matplotlib | 101 | [
"python",
"matplotlib",
"colormap"
] | 332 | 3,530 | 3 |
Change grid interval and specify tick labels I am trying to plot counts in gridded plots, but I haven't been able to figure out how to go about it. I want: to have dotted grids at an interval of 5; to have major tick labels only every 20; for the ticks to be outside the plot; and to have "counts" inside those grids. I ... | There are several problems in your code. First the big ones: You are creating a new figure and a new axes in every iteration of your loop → put fig = plt.figure and ax = fig.add_subplot(1,1,1) outside of the loop. Don't use the Locators. Call the functions ax.set_xticks() and ax.grid() with the correct keywords. With p... | 0.8 | matplotlib | https://stackoverflow.com/questions/24943991/change-grid-interval-and-specify-tick-labels | 280 | [
"python",
"matplotlib",
"xticks",
"gridlines",
"yticks"
] | 1,203 | 1,136 | 5 |
How to set xticks in subplots If I plot a single imshow plot I can use
```py
fig, ax = plt.subplots()
ax.imshow(data)
plt.xticks( [4, 14, 24], [5, 15, 25] )
```
to replace my xtick labels. Now, I am plotting 12 imshow plots using
```py
f, axarr = plt.subplots(4, 3)
axarr[i, j].imshow(data)
```
How can I change xtick... | There are two ways: Use the axes methods of the subplot object (e.g. ax.set_xticks and ax.set_xticklabels) or Use plt.sca to set the current axes for the pyplot state machine (i.e. the plt interface). As an example (this also illustrates using setp to change the properties of all of the subplots):
```
import matplotli... | 0.8 | matplotlib | https://stackoverflow.com/questions/19626530/how-to-set-xticks-in-subplots | 221 | [
"python",
"matplotlib",
"subplot"
] | 468 | 686 | 3 |
Getting vertical gridlines to appear in line plot in matplotlib I want to get both horizontal and vertical grid lines on my plot but only the horizontal grid lines are appearing by default. I am using a pandas.DataFrame from an sql query in python to generate a line plot with dates on the x-axis. I'm not sure why they ... | You may need to give boolean arg in your calls, e.g. use ax.yaxis.grid(True) instead of ax.yaxis.grid(). Additionally, since you are using both of them you can combine into ax.grid, which works on both, rather than doing it once for each dimension.
```
ax = plt.gca()
ax.grid(True)
```
That should sort you out. | 0.8 | matplotlib | https://stackoverflow.com/questions/16074392/getting-vertical-gridlines-to-appear-in-line-plot-in-matplotlib | 127 | [
"python",
"matplotlib",
"pandas"
] | 809 | 312 | 3 |
prevent plot from showing in jupyter notebook How can I prevent a specific plot to be shown in Jupyter notebook? I have several plots in a notebook but I want a subset of them to be saved to a file and not shown on the notebook as this slows considerably. A minimal working example for a Jupyter notebook is:
```
%matpl... | Perhaps just clear the axis, for example:
```
fig = plt.figure()
plt.plot(range(10))
fig.savefig("save_file_name.pdf")
plt.close()
```
This will not plot the output in inline mode. I can't work out if it is really clearing the data though. | 0.8 | matplotlib | https://stackoverflow.com/questions/18717877/prevent-plot-from-showing-in-jupyter-notebook | 163 | [
"python",
"matplotlib",
"jupyter-notebook",
"figures"
] | 878 | 240 | 4 |
How to generate random colors in matplotlib? What's the trivial example of how to generate random colors for passing to plotting functions? I'm calling scatter inside a loop and want each plot a different color.
```
for X,Y in data:
scatter(X, Y, c=??)
```
c: a color. c can be a single color format string, or a seq... | I'm calling scatter inside a loop and want each plot in a different color. Based on that, and on your answer: It seems to me that you actually want n distinct colors for your datasets; you want to map the integer indices 0, 1, ..., n-1 to distinct RGB colors. Something like: Here is the function to do it:
```
import m... | 0.8 | matplotlib | https://stackoverflow.com/questions/14720331/how-to-generate-random-colors-in-matplotlib | 201 | [
"python",
"matplotlib"
] | 676 | 1,526 | 2 |
Plotting images side by side using matplotlib I was wondering how I am able to plot images side by side using matplotlib for example something like this: The closest I got is this: This was produced by using this code:
```
f, axarr = plt.subplots(2,2)
axarr[0,0] = plt.imshow(image_datas[0])
axarr[0,1] = plt.imshow(ima... | The problem you face is that you try to assign the return of imshow (which is an matplotlib.image.AxesImage to an existing axes object. The correct way of plotting image data to the different axes in axarr would be
```
f, axarr = plt.subplots(2,2)
axarr[0,0].imshow(image_datas[0])
axarr[0,1].imshow(image_datas[1])
axa... | 0.8 | matplotlib | https://stackoverflow.com/questions/41793931/plotting-images-side-by-side-using-matplotlib | 182 | [
"python",
"matplotlib"
] | 872 | 717 | 2 |
Changing the color of an axis Is there a way to change the color of an axis (not the ticks) in matplotlib? I have been looking through the docs for Axes, Axis, and Artist, but no luck; the matplotlib gallery also has no hint. Any idea? | When using figures, you can easily change the spine color with:
```
ax.spines['bottom'].set_color('#dddddd')
ax.spines['top'].set_color('#dddddd')
ax.spines['right'].set_color('red')
ax.spines['left'].set_color('red')
```
Use the following to change only the ticks: which="both" changes both the major and minor tick c... | 0.8 | matplotlib | https://stackoverflow.com/questions/1982770/changing-the-color-of-an-axis | 237 | [
"python",
"matplotlib",
"axis"
] | 235 | 589 | 3 |
Histogram Matplotlib So I have a little problem. I have a data set in scipy that is already in the histogram format, so I have the center of the bins and the number of events per bin. How can I now plot is as a histogram. I tried just doing
```
bins, n=hist()
```
but it didn't like that. Any recommendations? | ```
import matplotlib.pyplot as plt
import numpy as np
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
hist, bins = np.histogram(x, bins=50)
width = 0.7 * (bins[1] - bins[0])
center = (bins[:-1] + bins[1:]) / 2
plt.bar(center, hist, align='center', width=width)
plt.show()
```
The object-oriented interface ... | 0.8 | matplotlib | https://stackoverflow.com/questions/5328556/histogram-matplotlib | 268 | [
"python",
"numpy",
"matplotlib",
"scipy",
"histogram"
] | 310 | 1,033 | 5 |
Linear regression with matplotlib / numpy I'm trying to generate a linear regression on a scatter plot I have generated, however my data is in list format, and all of the examples I can find of using polyfit require using arange. arange doesn't accept lists though. I have searched high and low about how to convert a li... | arange generates lists (well, numpy arrays); type help(np.arange) for the details. You don't need to call it on existing lists.
```py
```python
x = [1,2,3,4]
```
```python
y = [3,5,7,9]
```
```python
```
```python
m,b = np.polyfit(x, y, 1)
```
```python
m
#Output
#2.0000000000000009
```
```python
b
#Output
#0.... | 0.8 | matplotlib | https://stackoverflow.com/questions/6148207/linear-regression-with-matplotlib-numpy | 246 | [
"python",
"numpy",
"matplotlib",
"linear-regression",
"curve-fitting"
] | 685 | 821 | 5 |
Stop matplotlib repeating labels in legend Here is a very simplified example:
```
xvalues = [2,3,4,6]
for x in xvalues:
plt.axvline(x,color='b',label='xvalues')
plt.legend()
```
The legend will now show 'xvalues' as a blue line 4 times in the legend. Is there a more elegant way of fixing this than the following?... | plt.legend takes as parameters A list of axis handles which are Artist objects A list of labels which are strings These parameters are both optional defaulting to plt.gca().get_legend_handles_labels(). You can remove duplicate labels by putting them in a dictionary before calling legend. This is because dicts can't hav... | 0.8 | matplotlib | https://stackoverflow.com/questions/13588920/stop-matplotlib-repeating-labels-in-legend | 219 | [
"python",
"matplotlib",
"legend"
] | 466 | 961 | 3 |
Why doesn't plt.imshow() display the image? I have this code, copied from a tutorial:
```
import numpy as np
np.random.seed(123)
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from ke... | The solution was as simple as adding plt.show() at the end of the code snippet:
```
import numpy as np
np.random.seed(123)
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras.da... | 0.8 | matplotlib | https://stackoverflow.com/questions/42812230/why-doesnt-plt-imshow-display-the-image | 257 | [
"python",
"matplotlib",
"keras"
] | 946 | 488 | 3 |
How to add a second x-axis I have a very simple question. I need to have a second x-axis on my plot and I want that this axis has a certain number of tics that correspond to certain position of the first axis. Let's try with an example. Here I am plotting the dark matter mass as a function of the expansion factor, defi... | I'm taking a cue from the comments in @Dhara's answer, it sounds like you want to set a list of new_tick_locations by a function from the old x-axis to the new x-axis. The tick_function below takes in a numpy array of points, maps them to a new value and formats them:
```
import numpy as np
import matplotlib.pyplot as... | 0.8 | matplotlib | https://stackoverflow.com/questions/10514315/how-to-add-a-second-x-axis | 157 | [
"python",
"matplotlib",
"twiny"
] | 623 | 788 | 3 |
How to set the range of y-axis for a seaborn boxplot [duplicate] This question already has answers here: How to set the axis limits in Matplotlib? (10 answers) Closed 2 years ago. From the official seaborn documentation, I learned that you can create a boxplot as below:
```py
import seaborn as sns
sns.set_style("white... | It is standard matplotlib.pyplot:
```
import matplotlib.pyplot as plt
plt.ylim(10, 40)
```
Or simpler, as mwaskom comments below:
```
ax.set(ylim=(10, 40))
``` | 0.8 | matplotlib | https://stackoverflow.com/questions/33227473/how-to-set-the-range-of-y-axis-for-a-seaborn-boxplot | 174 | [
"python",
"matplotlib",
"plot",
"seaborn",
"boxplot"
] | 568 | 162 | 5 |
How to forget previous plots - how can I flush/refresh? How do you get matplotlib.pyplot to "forget" previous plots I am trying to plot multiple time using matplotlib.pyplot The code looks like this:
```
def plottest():
import numpy as np
import matplotlib.pyplot as plt
a=np.random.rand(10,)
b=np.ran... | I would rather use plt.clf() after every plt.show() to just clear the current figure instead of closing and reopening it, keeping the window size and giving you a better performance and much better memory usage. Similarly, you could do plt.cla() to just clear the current axes. To clear a specific axes, useful when you ... | 0.8 | matplotlib | https://stackoverflow.com/questions/17106288/how-to-forget-previous-plots-how-can-i-flush-refresh | 137 | [
"python",
"matplotlib"
] | 1,213 | 455 | 2 |
How to draw a line with matplotlib? I cannot find a way to draw an arbitrary line with matplotlib Python library. It allows to draw horizontal and vertical lines (with matplotlib.pyplot.axhline and matplotlib.pyplot.axvline, for example), but i do not see how to draw a line through two given points (x1, y1) and (x2, y2... | This will draw a line that passes through the points (-1, 1) and (12, 4), and another one that passes through the points (1, 3) et (10, 2) x1 are the x coordinates of the points for the first line, y1 are the y coordinates for the same -- the elements in x1 and y1 must be in sequence. x2 and y2 are the same for the oth... | 0.8 | matplotlib | https://stackoverflow.com/questions/36470343/how-to-draw-a-line-with-matplotlib | 128 | [
"python",
"python-3.x",
"matplotlib"
] | 361 | 1,357 | 3 |
Relationship between dpi and figure size I have created a figure using matplotlib but I have realized the plot axis and the drawn line gets zoomed out. Reading this earlier discussion thread, it explains how to set the figure size.
```
fig, ax = plt.subplots()
fig.set_size_inches(3, 1.5)
plt.savefig(file.jpeg, edgecol... | Figure size (figsize) determines the size of the figure in inches. This gives the amount of space the axes (and other elements) have inside the figure. The default figure size is (6.4, 4.8) inches in matplotlib 2. A larger figure size will allow for longer texts, more axes or more ticklabels to be shown. Dots per inche... | 0.8 | matplotlib | https://stackoverflow.com/questions/47633546/relationship-between-dpi-and-figure-size | 243 | [
"matplotlib",
"plot",
"graph",
"visualization"
] | 912 | 2,266 | 4 |
Get matplotlib color cycle state Is it possible to query the current state of the matplotlib color cycle? In other words is there a function get_cycle_state that will behave in the following way?
```
```python
plot(x1, y1)
```
```python
plot(x2, y2)
```
```python
state = get_cycle_state()
```
```python
print state... | Accessing the color cycle iterator There's no "user-facing" (a.k.a. "public") method to access the underlying iterator, but you can access it through "private" (by convention) methods. However, you'd can't get the state of an iterator without changing it. Setting the color cycle Quick aside: You can set the color/prope... | 0.8 | matplotlib | https://stackoverflow.com/questions/13831549/get-matplotlib-color-cycle-state | 130 | [
"python",
"matplotlib"
] | 493 | 3,178 | 2 |
How do I write a Latex formula in the legend of a plot using Matplotlib inside a .py file? I am writing a script in Python (.py file) and I am using Matplotlib to plot an array. I want to add a legend with a formula to the plot, but I haven't been able to do it. I have done this before in IPython or the terminal. In th... | The easiest way is to assign the label when you plot the data, e.g.:
```
import matplotlib.pyplot as plt
ax = plt.gca() # or any other way to get an axis object
ax.plot(x, y, label=r'$\sin (x)$')
ax.legend()
``` | 0.8 | matplotlib | https://stackoverflow.com/questions/14016217/how-do-i-write-a-latex-formula-in-the-legend-of-a-plot-using-matplotlib-inside-a | 118 | [
"python",
"matplotlib",
"latex"
] | 490 | 214 | 3 |
Drawing average line in histogram I am drawing a histogram using matplotlib in python, and would like to draw a line representing the average of the dataset, overlaid on the histogram as a dotted line (or maybe some other color would do too). Any ideas on how to draw a line overlaid on the histogram? I am using the plo... | You can use plot or vlines to draw a vertical line, but to draw a vertical line from the bottom to the top of the y axis, axvline is the probably the simplest function to use. Here's an example:
```
```python
import numpy as np
```
```python
import matplotlib.pyplot as plt
```
```python
np.random.seed(6789)
```
``... | 0.8 | matplotlib | https://stackoverflow.com/questions/16180946/drawing-average-line-in-histogram | 178 | [
"python",
"matplotlib",
"axis"
] | 428 | 560 | 3 |
How to remove lines in a Matplotlib plot How can I remove a line (or lines) of a matplotlib axes in such a way as it actually gets garbage collected and releases the memory back? The below code appears to delete the line, but never releases the memory (even with explicit calls to gc.collect())
```
from matplotlib impo... | This is a very long explanation that I typed up for a coworker of mine. I think it would be helpful here as well. Be patient, though. I get to the real issue that you are having toward the end. Just as a teaser, it's an issue of having extra references to your Line2D objects hanging around. WARNING: One other note befo... | 0.8 | matplotlib | https://stackoverflow.com/questions/4981815/how-to-remove-lines-in-a-matplotlib-plot | 95 | [
"python",
"matplotlib",
"plot"
] | 862 | 4,588 | 3 |
Matplotlib/Pyplot: How to zoom subplots together? I have plots of 3-axis accelerometer time-series data (t,x,y,z) in separate subplots I'd like to zoom together. That is, when I use the "Zoom to Rectangle" tool on one plot, when I release the mouse all 3 plots zoom together. Previously, I simply plotted all 3 axes on a... | The easiest way to do this is by using the sharex and/or sharey keywords when creating the axes:
```
from matplotlib import pyplot as plt
ax1 = plt.subplot(2,1,1)
ax1.plot(...)
ax2 = plt.subplot(2,1,2, sharex=ax1)
ax2.plot(...)
``` | 0.8 | matplotlib | https://stackoverflow.com/questions/4200586/matplotlib-pyplot-how-to-zoom-subplots-together | 161 | [
"zooming",
"matplotlib"
] | 999 | 233 | 2 |
Is there a parameter in matplotlib/pandas to have the Y axis of a histogram as percentage? I would like to compare two histograms by having the Y axis show the percentage of each column from the overall dataset size instead of an absolute value. Is that possible? I am using Pandas and matplotlib. Thanks | The density=True (normed=True for matplotlib < 2.2.0) returns a histogram for which np.sum(pdf * np.diff(bins)) equals 1. If you want the sum of the histogram to be 1 you can use Numpy's histogram() and normalize the results yourself.
```
x = np.random.randn(30)
fig, ax = plt.subplots(1,2, figsize=(10,4))
ax[0].hist... | 0.8 | matplotlib | https://stackoverflow.com/questions/17874063/is-there-a-parameter-in-matplotlib-pandas-to-have-the-y-axis-of-a-histogram-as-p | 108 | [
"python",
"pandas",
"matplotlib"
] | 304 | 623 | 3 |
Plotting a 3d cube, a sphere and a vector I search how to plot something with less instruction as possible with Matplotlib but I don't find any help for this in the documentation. I want to plot the following things: a wireframe cube centered in 0 with a side length of 2 a "wireframe" sphere centered in 0 with a radius... | It is a little complicated, but you can draw all the objects by the following code:
```
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")
# draw cube
r = [-1, ... | 0.8 | matplotlib | https://stackoverflow.com/questions/11140163/plotting-a-3d-cube-a-sphere-and-a-vector | 216 | [
"python",
"matplotlib",
"geometry",
"matplotlib-3d"
] | 431 | 1,369 | 4 |
How to show two figures using matplotlib? I have some troubles while drawing two figures at the same time, not shown in a single plot. But according to the documentation, I wrote the code and only the figure one shows. I think maybe I lost something important. Could anyone help me to figure out? Thanks. (The *tlist_fir... | Alternatively to calling plt.show() at the end of the script, you can also control each figure separately doing:
```
f = plt.figure(1)
plt.hist........
............
f.show()
g = plt.figure(2)
plt.hist(........
................
g.show()
raw_input()
```
In this case you must call raw_input to keep the figures alive. T... | 0.8 | matplotlib | https://stackoverflow.com/questions/7744697/how-to-show-two-figures-using-matplotlib | 110 | [
"python",
"matplotlib"
] | 1,396 | 438 | 2 |
Putting newline in matplotlib label with TeX in Python? How can I add a newline to a plot's label (e.g. xlabel or ylabel) in matplotlib? For example,
```
plt.bar([1, 2], [4, 5])
plt.xlabel("My x label")
plt.ylabel(r"My long label with $\Sigma_{C}$ math \n continues here")
```
Ideally I'd like the y-labeled to be cente... | You can have the best of both worlds: automatic "escaping" of LaTeX commands and newlines:
```
plt.ylabel(r"My long label with unescaped {\LaTeX} $\Sigma_{C}$ math"
"\n" # Newline: the backslash is interpreted as usual
r"continues here with $\pi$")
```
(instead of using three lines, separating t... | 0.8 | matplotlib | https://stackoverflow.com/questions/2660319/putting-newline-in-matplotlib-label-with-tex-in-python | 143 | [
"python",
"plot",
"graphing",
"matplotlib"
] | 434 | 534 | 4 |
How to display custom values on a bar plot I'm looking to see how to do two things in Seaborn with using a bar chart to display values that are in the dataframe, but not in the graph. I'm looking to display the values of one field in a dataframe while graphing another. For example, below, I'm graphing 'tip', but I woul... | New in matplotlib 3.4.0 There is now a built-in Axes.bar_label to automatically label bar containers:
```py
ax = sns.barplot(x='day', y='tip', data=groupedvalues)
ax.bar_label(ax.containers[0]) # only 1 container needed unless using `hue`
```
For custom labels (e.g., tip bars with total_bill values), use the labels pa... | 0.8 | matplotlib | https://stackoverflow.com/questions/43214978/how-to-display-custom-values-on-a-bar-plot | 165 | [
"python",
"pandas",
"matplotlib",
"seaborn",
"bar-chart"
] | 2,721 | 1,689 | 5 |
Matplotlib scatter plot legend I created a 4D scatter plot graph to represent different temperatures in a specific area. When I create the legend, the legend shows the correct symbol and color but adds a line through it. The code I'm using is:
```
colors=['b', 'c', 'y', 'm', 'r']
lo = plt.Line2D(range(10), range(10), ... | 2D scatter plot Using the scatter method of the matplotlib.pyplot module should work (at least with matplotlib 1.2.1 with Python 2.7.5), as in the example code below. Also, if you are using scatter plots, use scatterpoints=1 rather than numpoints=1 in the legend call to have only one point for each legend entry. In the... | 0.8 | matplotlib | https://stackoverflow.com/questions/17411940/matplotlib-scatter-plot-legend | 163 | [
"python",
"matplotlib",
"legend",
"scatter-plot"
] | 1,930 | 2,538 | 4 |
How to add line based on slope and intercept In R, there is a function called abline in which a line can be drawn on a plot based on the specification of the intercept (first argument) and the slope (second argument). For instance,
```
plot(1:10, 1:10)
abline(0, 1)
```
where the line with an intercept of 0 and the slo... | A lot of these solutions are focusing on adding a line to the plot that fits the data. Here's a simple solution for adding an arbitrary line to the plot based on a slope and intercept.
```
import matplotlib.pyplot as plt
import numpy as np
def abline(slope, intercept):
"""Plot a line from slope and intercept... | 0.8 | matplotlib | https://stackoverflow.com/questions/7941226/how-to-add-line-based-on-slope-and-intercept | 128 | [
"python",
"matplotlib"
] | 403 | 462 | 2 |
How to use matplotlib tight layout with Figure? [duplicate] This question already has answers here: Improve subplot size/spacing with many subplots (12 answers) Closed 2 years ago. I found tight_layout function for pyplot and want to use it. In my application I embed matplotlib plots into Qt GUI and use figure and not ... | Just call fig.tight_layout() as you normally would. (pyplot is just a convenience wrapper. In most cases, you only use it to quickly generate figure and axes objects and then call their methods directly.) There shouldn't be a difference between the QtAgg backend and the default backend (or if there is, it's a bug). E.g... | 0.8 | matplotlib | https://stackoverflow.com/questions/9603230/how-to-use-matplotlib-tight-layout-with-figure | 152 | [
"python",
"matplotlib",
"figure"
] | 433 | 1,060 | 3 |
Can i cycle through line styles in matplotlib I know how to cycle through a list of colors in matplotlib. But is it possible to do something similar with line styles (plain, dotted, dashed, etc.)? I'd need to do that so my graphs would be easier to read when printed. Any suggestions how to do that? | Something like this might do the trick:
```
import matplotlib.pyplot as plt
from itertools import cycle
lines = ["-","--","-.",":"]
linecycler = cycle(lines)
plt.figure()
for i in range(10):
x = range(i,i+10)
plt.plot(range(10),x,next(linecycler))
plt.show()
```
Result: Edit for newer version (v2.22)
```
impo... | 0.8 | matplotlib | https://stackoverflow.com/questions/7799156/can-i-cycle-through-line-styles-in-matplotlib | 136 | [
"python",
"matplotlib"
] | 299 | 810 | 2 |
Barchart with vertical ytick labels I'm using matplotlib to generate a (vertical) barchart. The problem is my labels are rather long. Is there any way to display them vertically, either in the bar or above it or below it? | Do you mean something like this:
```
```python
from matplotlib import *
```
```python
plot(xrange(10))
```
```python
yticks(xrange(10), rotation='vertical')
#Output
#```
#? In general, to show any text in matplotlib with a vertical orientation, you can add the keyword rotation='vertical'. For further options, you c... | 0.8 | matplotlib | https://stackoverflow.com/questions/1221108/barchart-with-vertical-ytick-labels | 116 | [
"python",
"matplotlib",
"bar-chart",
"yaxis"
] | 221 | 705 | 4 |
What are the differences between add_axes and add_subplot? In a previous answer it was recommended to me to use add_subplot instead of add_axes to show axes correctly, but searching the documentation I couldn't understand when and why I should use either one of these functions. Can anyone explain the differences? | Common grounds Both, add_axes and add_subplot add an axes to a figure. They both return a (subclass of a) matplotlib.axes.Axes object. However, the mechanism which is used to add the axes differs substantially. add_axes The calling signature of add_axes is add_axes(rect), where rect is a list [x0, y0, width, height] de... | 0.8 | matplotlib | https://stackoverflow.com/questions/43326680/what-are-the-differences-between-add-axes-and-add-subplot | 172 | [
"python",
"matplotlib",
"subplot",
"figure",
"axes"
] | 314 | 2,983 | 5 |
Automatically run %matplotlib inline in IPython Notebook Every time I launch IPython Notebook, the first command I run is
```
%matplotlib inline
```
Is there some way to change my config file so that when I launch IPython, it is automatically in this mode? | The configuration way IPython has profiles for configuration, located at ~/.ipython/profile_*. The default profile is called profile_default. Within this folder there are two primary configuration files: ipython_config.py ipython_kernel_config.py Add the inline option for matplotlib to ipython_kernel_config.py:
```
c ... | 0.8 | matplotlib | https://stackoverflow.com/questions/21176731/automatically-run-matplotlib-inline-in-ipython-notebook | 87 | [
"python",
"matplotlib",
"jupyter-notebook"
] | 257 | 934 | 3 |
How to create grouped boxplots Is there a way to group boxplots in matplotlib? Assume we have three groups "A", "B", and "C" and for each we want to create a boxplot for both "apples" and "oranges". If a grouping is not possible directly, we can create all six combinations and place them linearly side by side. What wou... | How about using colors to differentiate between "apples" and "oranges" and spacing to separate "A", "B" and "C"? Something like this:
```
from pylab import plot, show, savefig, xlim, figure, \
hold, ylim, legend, boxplot, setp, axes
# function for setting the colors of the box plots pairs
def setBoxCo... | 0.8 | matplotlib | https://stackoverflow.com/questions/16592222/how-to-create-grouped-boxplots | 119 | [
"python",
"matplotlib",
"boxplot"
] | 499 | 1,733 | 3 |
Superscript in Python plots I want to label my x axis at follows :
```
pylab.xlabel('metres 10^1')
```
But I don't want to have the ^ symbol included .
```
pylab.xlabel('metres 10$^{one}$')
```
This method works and will superscript letters but doesn't seem to work for numbers . If I try :
```
pylab.xlabel('metres 1... | You just need to have the full expression inside the $. Basically, you need "meters $10^1$". You don't need usetex=True to do this (or most any mathematical formula). You may also want to use a raw string (e.g. r"\t", vs "\t") to avoid problems with things like \n, \a, \b, \t, \f, etc. For example:
```
import matplotl... | 0.8 | matplotlib | https://stackoverflow.com/questions/21226868/superscript-in-python-plots | 164 | [
"python",
"matplotlib"
] | 442 | 1,199 | 2 |
How to draw grid lines behind matplotlib bar graph
```
x = ['01-02', '02-02', '03-02', '04-02', '05-02']
y = [2, 2, 3, 7, 2]
fig, ax = plt.subplots(1, 1)
ax.bar(range(len(y)), y, width=0.3,align='center',color='skyblue')
plt.xticks(range(len(y)), x, size='small')
plt.savefig('/home/user/graphimages/foo2.png')
plt.clo... | To add a grid you simply need to add ax.grid() If you want the grid to be behind the bars then add
```
ax.grid(zorder=0)
ax.bar(range(len(y)), y, width=0.3, align='center', color='skyblue', zorder=3)
```
The important part is that the zorder of the bars is greater than grid. Experimenting it seems zorder=3 is the lowe... | 0.8 | matplotlib | https://stackoverflow.com/questions/23357798/how-to-draw-grid-lines-behind-matplotlib-bar-graph | 147 | [
"python",
"matplotlib"
] | 387 | 638 | 2 |
How to hide axes and gridlines I would like to be able to hide the axes and gridlines on a 3D matplotlib graph. I want to do this because when zooming in and out the image gets pretty nasty. I'm not sure what code to include here but this is what I use to create the graph.
```
fig = plt.figure()
ax = fig.gca(projectio... | ```
# Hide grid lines
ax.grid(False)
# Hide axes ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
```
Note, you need matplotlib>=1.2 for set_zticks() to work. | 0.8 | matplotlib | https://stackoverflow.com/questions/45148704/how-to-hide-axes-and-gridlines | 181 | [
"python",
"matplotlib",
"matplotlib-3d"
] | 528 | 170 | 3 |
Pandas dataframe groupby plot I have a dataframe which is structured as:
```
Date ticker adj_close
0 2016-11-21 AAPL 111.730
1 2016-11-22 AAPL 111.800
2 2016-11-23 AAPL 111.230
3 2016-11-25 AAPL 111.790
4 2016-11-28 AAPL 111.570
...
8 2... | Simple plot, you can use:
```
df.plot(x='Date',y='adj_close')
```
Or you can set the index to be Date beforehand, then it's easy to plot the column you want:
```
df.set_index('Date', inplace=True)
df['adj_close'].plot()
```
If you want a chart with one series by ticker on it You need to groupby before:
```
df.set_in... | 0.8 | matplotlib | https://stackoverflow.com/questions/41494942/pandas-dataframe-groupby-plot | 158 | [
"python",
"pandas",
"matplotlib",
"time-series",
"seaborn"
] | 565 | 746 | 5 |
Histogram values of a Pandas Series I have some values in a Python Pandas Series (type: pandas.core.series.Series)
```
```python
series = pd.Series([0.0,950.0,-70.0,812.0,0.0,-90.0,0.0,0.0,-90.0,0.0,-64.0,208.0,0.0,-90.0,0.0,-80.0,0.0,0.0,-80.0,-48.0,840.0,-100.0,190.0,130.0,-100.0,-100.0,0.0,-50.0,0.0,-100.0,-100.0,... | You just need to use the histogram function of NumPy:
```
import numpy as np
count, division = np.histogram(series)
```
where division is the automatically calculated border for your bins and count is the population inside each bin. If you need to fix a certain number of bins, you can use the argument bins and specify... | 0.8 | matplotlib | https://stackoverflow.com/questions/13129618/histogram-values-of-a-pandas-series | 122 | [
"python",
"pandas",
"numpy",
"matplotlib"
] | 1,232 | 930 | 4 |
matplotlib: drawing lines between points ignoring missing data I have a set of data which I want plotted as a line-graph. For each series, some data is missing (but different for each series). Currently matplotlib does not draw lines which skip missing data: for example
```
import matplotlib.pyplot as plt
xs = range(... | You can mask the NaN values this way:
```
import numpy as np
import matplotlib.pyplot as plt
xs = np.arange(8)
series1 = np.array([1, 3, 3, None, None, 5, 8, 9]).astype(np.double)
s1mask = np.isfinite(series1)
series2 = np.array([2, None, 5, None, 4, None, 3, 2]).astype(np.double)
s2mask = np.isfinite(series2)
plt.p... | 0.8 | matplotlib | https://stackoverflow.com/questions/14399689/matplotlib-drawing-lines-between-points-ignoring-missing-data | 119 | [
"python",
"matplotlib"
] | 669 | 474 | 2 |
GridSpec with shared axes in Python This solution to another thread suggests using gridspec.GridSpec instead of plt.subplots. However, when I share axes between subplots, I usually use a syntax like the following
```
fig, axes = plt.subplots(N, 1, sharex='col', sharey=True, figsize=(3,18))
```
How can I specify sharex... | First off, there's an easier workaround for your original problem, as long as you're okay with being slightly imprecise. Just reset the top extent of the subplots to the default after calling tight_layout:
```
fig, axes = plt.subplots(ncols=2, sharey=True)
plt.setp(axes, title='Test')
fig.suptitle('An overall title', ... | 0.8 | matplotlib | https://stackoverflow.com/questions/22511550/gridspec-with-shared-axes-in-python | 95 | [
"python",
"matplotlib"
] | 353 | 1,131 | 2 |
Fitting a Normal distribution to 1D data I have a 1 dimensional array. I can compute the "mean" and "standard deviation" of this sample and plot the "Normal distribution" but I have a problem: I want to plot the data and Normal distribution in the same figure. I dont know how to plot both the data and the normal distri... | You can use matplotlib to plot the histogram and the PDF (as in the link in @MrE's answer). For fitting and for computing the PDF, you can use scipy.stats.norm, as follows.
```
import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt
# Generate some data for this demonstration.
data = norm.rvs... | 0.8 | matplotlib | https://stackoverflow.com/questions/20011122/fitting-a-normal-distribution-to-1d-data | 191 | [
"python",
"numpy",
"matplotlib",
"scipy"
] | 474 | 755 | 4 |
Delete a subplot I'm trying to figure out a way of deleting (dynamically) subplots in matplotlib. I see they have a remove method, but I get the error
```
NotImplementedError: cannot remove artist
```
I'm surprised that I can't find this anywhere. Does anyone know how to do this?
```py
from matplotlib import pyplot a... | Use fig.delaxes or plt.delaxes to remove unwanted subplots
```py
fig, axs = plt.subplots(1,3)
axs[0].plot([1,2],[3,4])
axs[2].plot([0,1],[2,3])
fig.delaxes(axs[1])
plt.draw()
plt.tight_layout()
``` | 0.8 | matplotlib | https://stackoverflow.com/questions/14694501/delete-a-subplot | 167 | [
"python",
"matplotlib",
"subplot"
] | 441 | 200 | 3 |
Keras - Plot training, validation and test set accuracy I want to plot the output of this simple neural network:
```
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
history = model.fit(x_test, y_test, nb_epoch=10, validation_split=0.2, shuffle=True)
model.test_on_batch(x_test, y_test... | ```
import keras
from matplotlib import pyplot as plt
history = model1.fit(train_x, train_y,validation_split = 0.1, epochs=50, batch_size=4)
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'val'],... | 0.8 | matplotlib | https://stackoverflow.com/questions/41908379/keras-plot-training-validation-and-test-set-accuracy | 152 | [
"python",
"matplotlib",
"keras"
] | 1,142 | 554 | 3 |
creating over 20 unique legend colors using matplotlib I am plotting 20 different lines on a single plot using matplotlib. I use a for loop for plotting and label every line with its key and then use the legend function
```
for key in dict.keys():
plot(x,dict[key], label = key)
graph.legend()
```
But using this wa... | The answer to your question is related to two other SO questions. The answer to How to pick a new color for each plotted line within a figure in matplotlib? explains how to define the default list of colors that is cycled through to pick the next color to plot. This is done with the Axes.set_color_cycle method. You wan... | 0.8 | matplotlib | https://stackoverflow.com/questions/8389636/creating-over-20-unique-legend-colors-using-matplotlib | 149 | [
"python",
"matplotlib",
"legend"
] | 481 | 2,040 | 3 |
Reset color cycle in Matplotlib Say I have data about 3 trading strategies, each with and without transaction costs. I want to plot, on the same axes, the time series of each of the 6 variants (3 strategies * 2 trading costs). I would like the "with transaction cost" lines to be plotted with alpha=1 and linewidth=1 whi... | In Matplotlib <1.5.0, you can reset the colorcycle to the original with Axes.set_color_cycle. Looking at the code for this, there is a function to do the actual work:
```
def set_color_cycle(self, clist=None):
if clist is None:
clist = rcParams['axes.color_cycle']
self.color_cycle = itertools.cycle(cli... | 0.8 | matplotlib | https://stackoverflow.com/questions/24193174/reset-color-cycle-in-matplotlib | 121 | [
"python",
"matplotlib",
"pandas"
] | 1,012 | 1,186 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.