Line2D costum legend only one point [duplicate] - python

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()

Related

How to control colorbar position when using subplots in Matplotlib [duplicate]

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)

Seaborn: how to make subplots with multiple line charts? sns.relplot doesn't seem to support it? [duplicate]

This question already has an answer here:
seaborn is not plotting within defined subplots
(1 answer)
Closed 1 year ago.
The seaborn documentation makes a distinction between figure-level and axes-level functions: https://seaborn.pydata.org/introduction.html#figure-level-and-axes-level-functions
I understand that functions like sns.boxplot can take an axis as argument, and can therefore be used within subplots.
But how about sns.relplot() ? Is there no way to put that into subplots?
More generally, is there any way to get seaborn to generate line plots within subplots?
For example, this doesn't work:
fig,ax=plt.subplots(2)
sns.relplot(x,y, ax=ax[0])
because relplot doesn't take axes as an argument.
Well that's not true. You can indeed pass axis objects to relplot. Below is a minimal answer. The key point here is to close the empty axis objects returned by relplot. You can then also use ax[0] or ax[1] to add additional curves to your individual subfigures just like you would do with matplotlib.
import seaborn as sns
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2)
xdata = np.arange(50)
sns.set(style="ticks")
tips = sns.load_dataset("tips")
g1 = sns.relplot(x="total_bill", y="tip", hue="day", data=tips, ax=ax[0])
g2 = sns.relplot(x="total_bill", y="tip", hue="day", data=tips, ax=ax[1])
# Now you can add any curves to individual axis objects
ax[0].plot(xdata, xdata/5)
# You will have to close the additional empty figures returned by replot
plt.close(g1.fig)
plt.close(g2.fig)
plt.tight_layout()
You can also make line plot solely using seaborn as
import seaborn as sns
import numpy as np
x = np.linspace(0, 5, 100)
y = x**2
ax = sns.lineplot(x, y)
ax.set_xlabel('x-label')
ax.set_ylabel('y-label')

Funcanimation of matplotlib makes multiple colorbar [duplicate]

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)

Seaborn - remove spacing from DataFrame histogram [duplicate]

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()

How to set ax.legend fontsize? [duplicate]

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))

Categories

Resources