This question already has answers here:
How to change legend fontsize with matplotlib.pyplot
(9 answers)
Closed 6 years ago.
Here is my code
import os,sys
import Image
import matplotlib.pyplot as plt
from matplotlib.pyplot import *
from matplotlib.font_manager import FontProperties
jpgfile = Image.open("t002.jpg")
# Set up the figure and axes.
fig = plt.figure(figsize=(18,10)) # ...or whatever size you want.
ax = fig.add_subplot(111)
ax.legend(fontsize=18)
# Draw things.
plt.imshow(jpgfile) # Unlike plot and scatter, not a method on ax.
ax.set_xlabel('normalized resistivities')
ax.set_ylabel('normalized velocities')
ax.set_xticks([]); ax.set_yticks([])
# Save and show.
plt.savefig("fig.jpg")
plt.show()
But
/usr/local/lib/python2.7/dist-packages/matplotlib/axes/_axes.py:519: UserWarning: No labelled objects found. Use label='...' kwarg on individual plots
How should I set the labels?
Legend fonts are customized by providing a dict of font property-value pairs to the 'prop' kwarg:
ax.legend(prop=dict(size=18))
Related
This question already has answers here:
matplotlib Legend Markers Only Once
(2 answers)
Closed 3 years ago.
I am trying to make a costum legend in a Basemap plot so was considering using Line2D. It works ok, but I want that the legend only consist of one marker and no line, instead of a line between two markers (see below).
Here is the most important part of the code I use to plot this costum legend:
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt
fig,ax = plt.subplots()
legend_elements = [Line2D([0],[0],marker='o',markersize=10,color='green',label='Label1'),
Line2D([0],[0],marker='s',markersize=12,color='red',label='Label2')]
ax.legend(handles=legend_elements,loc=2)
plt.show()
use numpoints= in the legend() call to control the number of points shown for a Line2D object. A line is still shown though. If you want to remove the line, set its width to 0 when creating the Line2D.
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt
fig,ax = plt.subplots()
legend_elements = [Line2D([0],[0],marker='o',markersize=10,color='green',label='Label1', lw=0),
Line2D([0],[0],marker='s',markersize=12,color='red',label='Label2', lw=0)]
ax.legend(handles=legend_elements,loc=2, numpoints=1)
plt.show()
This question already has answers here:
Modify tick label text
(13 answers)
Closed 5 months 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.
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'])
As of matplotlib 3.5.0
set_xticklabels is now discouraged:
The use of this method is discouraged because of the dependency on tick positions. In most cases, you'll want to use set_xticks(positions, labels) instead.
Now set_xticks includes a new labels param to set ticks and labels simultaneously:
ax = sns.lineplot(data=df)
ax.set_xticks(range(len(df)), labels=range(2011, 2019))
# ^^^^^^
This question already has an answer here:
adjusting subplot with a colorbar
(1 answer)
Closed 3 years ago.
I am trying to use Matplotlib to plot a time series along with its spectrogram and its associated colorbar.
Below is a MCVE:
import numpy as np
import matplotlib.pyplot as plt
import scipy.signal as scignal
import random
array=np.random.random(10000)
t,f,Sxx=scignal.spectrogram(array,fs=100)
plt.subplot(211)
plt.plot(array)
plt.subplot(212)
plt.pcolormesh(Sxx)
plt.colorbar()
This code yields the following figure:
However, I would like both subplots to have the same size:
I thought of changing the orientation of the colorbar using plt.colorbar(orientation='horizontal') but I am not satisfied with the result as the subplots end up not having the same height.
Any help will be appreciated!
The reason this happens is that plt.colorbar creates a new Axes object, which "steals" space from the lower Axes (this is the reason making a horizontal colourbar also affects the two original plots).
There are a few ways to work around this; one is to create a Figure with four Axes, allocate most of the space to the left ones, and just make one invisible:
import numpy as np
import matplotlib.pyplot as plt
import scipy.signal as scignal
import random
array = np.random.random(10000)
t, f, Sxx = scignal.spectrogram(array,fs=100)
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(5, 6), gridspec_kw={'width_ratios': [19, 1]})
(ax1, blank), (ax2, ax_cb) = axes
blank.set_visible(False)
ax1.plot(array)
m = ax2.pcolormesh(Sxx)
fig.colorbar(m, cax=ax_cb)
This question already has answers here:
Maintaining one colorbar for maptlotlib FuncAnimation
(3 answers)
Closed 4 years ago.
I want to make gif animation with FuncAnimation of matplotlib.
Here is the code.
However the output image contains multiple colorbars like this(link)
Does anyone know how to fix this problem ?
If I set
plt.colorbar()
just after or before
ani = animation.FuncAnimation(fig, update, interval=100 ,frames=400)
, it returns
RuntimeError: No mappable was found to use for colorbar creation. First define a mappable such as an image (with imshow) or a contour set (with contourf).
If I subsitute plt.colorbar() with if(k==0): plt.colorbar(), image contains same 2 colorbars.
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from PIL import Image
import moviepy.editor as edit
from mpl_toolkits.axes_grid1 import make_axes_locatable
def update(k):
plt.cla() # clear axis
#updating Val...
plt.contourf(X0, Y0, Val, cmap = "bwr")
plt.colorbar()
plt.axes().set_aspect("equal")
plt.title("title-name")
fig = plt.figure()
ani = animation.FuncAnimation(fig, update, interval=100 ,frames=400)
ani.save("out.gif", writer='imagemagick')
I add
plt.colorbar(plt.contourf(X0,Y0,charge,cmap="bwr",levels=np.linspace(-1,1,100,endpoint=True)))
just after
fig=plt.figure()
and it works successfully.
This method is adopted from Mr. ImportanceOfBeingErnest's answer(Maintaining one colorbar for maptlotlib FuncAnimation)
This question already has answers here:
How can I change the x axis in matplotlib so there is no white space?
(2 answers)
Closed 5 years ago.
I am trying to generate a histogram from a DataFrame with seaborn enabled via the DataFrame.hist method, but I keep finding extra space added to either side of the histogram itself, as seen by the red arrows in the below picture:
How can I remove these spaces? Code to reproduce this graph is as follows:
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from random import seed, choice
seed(0)
df = pd.DataFrame([choice(range(250)) for _ in range(100)], columns=['Values'])
bins = np.arange(0, 260, 10)
df['Values'].hist(bins=bins)
plt.tight_layout()
plt.show()
plt.tight_layout() only has an effect for the "outer margins" of your plot (tick marks, ax labels etc.).
By default matplotlib's hist leaves an inner margin around the hist bar-plot. To disable you can do this:
ax = df['Values'].hist(bins=bins)
ax.margins(x=0)
plt.show()