Is it possible to plot a line with variable line width in matplotlib? For example:
from pylab import *
x = [1, 2, 3, 4, 5]
y = [1, 2, 2, 0, 0]
width = [.5, 1, 1.5, .75, .75]
plot(x, y, linewidth=width)
This doesn't work because linewidth expects a scalar.
Note: I'm aware of *fill_between()* and *fill_betweenx()*. Because these only fill in x or y direction, these do not do justice to cases where you have a slanted line. It is desirable for the fill to always be normal to the line. That is why a variable width line is sought.
Use LineCollections. A way to do it along the lines of this Matplotlib example is
import numpy as np
from matplotlib.collections import LineCollection
import matplotlib.pyplot as plt
x = np.linspace(0,4*np.pi,10000)
y = np.cos(x)
lwidths=1+x[:-1]
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
lc = LineCollection(segments, linewidths=lwidths,color='blue')
fig,a = plt.subplots()
a.add_collection(lc)
a.set_xlim(0,4*np.pi)
a.set_ylim(-1.1,1.1)
fig.show()
An alternative to Giulio Ghirardo's answer which divides the lines in segments you can use matplotlib's in-built scatter function which construct the line by using circles instead:
from matplotlib import pyplot as plt
import numpy as np
x = np.linspace(0,10,10000)
y = 2 - 0.5*np.abs(x-4)
lwidths = (1+x)**2 # scatter 'o' marker size is specified by area not radius
plt.scatter(x,y, s=lwidths, color='blue')
plt.xlim(0,9)
plt.ylim(0,2.1)
plt.show()
In my experience I have found two problems with dividing the line into segments:
For some reason the segments are always divided by very thin white lines. The colors of these lines get blended with the colors of the segments when using a very large amount of segments. Because of this the color of the line is not the same as the intended one.
It doesn't handle very well very sharp discontinuities.
You can plot each segment of the line separately, with its separate line width, something like:
from pylab import *
x = [1, 2, 3, 4, 5]
y = [1, 2, 2, 0, 0]
width = [.5, 1, 1.5, .75, .75]
for i in range(len(x)-1):
plot(x[i:i+2], y[i:i+2], linewidth=width[i])
show()
gg349's answer works nicely but cuts the line into many pieces, which can often creates bad rendering.
Here is an alternative example that generates continuous lines when the width is homogeneous:
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1)
xs = np.cos(np.linspace(0, 8 * np.pi, 200)) * np.linspace(0, 1, 200)
ys = np.sin(np.linspace(0, 8 * np.pi, 200)) * np.linspace(0, 1, 200)
widths = np.round(np.linspace(1, 5, len(xs)))
def plot_widths(xs, ys, widths, ax=None, color='b', xlim=None, ylim=None,
**kwargs):
if not (len(xs) == len(ys) == len(widths)):
raise ValueError('xs, ys, and widths must have identical lengths')
fig = None
if ax is None:
fig, ax = plt.subplots(1)
segmentx, segmenty = [xs[0]], [ys[0]]
current_width = widths[0]
for ii, (x, y, width) in enumerate(zip(xs, ys, widths)):
segmentx.append(x)
segmenty.append(y)
if (width != current_width) or (ii == (len(xs) - 1)):
ax.plot(segmentx, segmenty, linewidth=current_width, color=color,
**kwargs)
segmentx, segmenty = [x], [y]
current_width = width
if xlim is None:
xlim = [min(xs), max(xs)]
if ylim is None:
ylim = [min(ys), max(ys)]
ax.set_xlim(xlim)
ax.set_ylim(ylim)
return ax if fig is None else fig
plot_widths(xs, ys, widths)
plt.show()
Related
I wish to modify the 2D line in my legend to plot as line segments (or another method like patches) that will display the range of my colormap (here viridis_r) instead of a singular color. While the third variable (radius) is included in the colorbar, having it displayed in the legend as well will be informative when I add more complications to the plot. Thanks!
fig, ax = plt.subplots()
radii = [1,2,3,4,5]
angle = np.linspace(0, 2 * np.pi, 150)
cmap = plt.get_cmap('viridis_r')
norm = plt.Normalize(radii[0], radii[-1])
m = plt.cm.ScalarMappable(cmap=cmap)
m.set_array(radii)
for radius in radii:
x = radius * np.cos(angle)
y = radius * np.sin(angle)
ax.plot(x, y, color=cmap(norm(radius)))
radius_2Dline = plt.Line2D((0, 1), (0, 0), color='k', linewidth=2)
ax.legend([radius_2Dline],['Radius'], loc='best')
ax.set_aspect( 1 )
fig.colorbar(m).set_label('Radius', size=15)
plt.show()
The following approach uses the "tuple legend handler". That handler puts a list of legend handles (in this case the circles drawn via ax.plot). Setting ndivide=None will draw one short line for each element in the list. The padding can be set to 0 to avoid gaps between these short lines. The default handlelength might be too small to properly see these special handles; therefore, the example code below increases it a bit.
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerTuple
import numpy as np
fig, ax = plt.subplots()
radii = [1, 2, 3, 4, 5]
angle = np.linspace(0, 2 * np.pi, 150)
cmap = plt.get_cmap('viridis_r')
norm = plt.Normalize(radii[0], radii[-1])
lines = [] # list of lines to be used for the legend
for radius in radii:
x = radius * np.cos(angle)
y = radius * np.sin(angle)
line, = ax.plot(x, y, color=cmap(norm(radius)))
lines.append(line)
ax.legend(handles=[tuple(lines)], labels=['Radius'],
handlelength=3, handler_map={tuple: HandlerTuple(ndivide=None, pad=0)})
ax.set_aspect('equal')
plt.tight_layout()
plt.show()
I am not sure if this is your goal but here is a stab at it. Following this answer, you can make a 'fake' legend with a colormap.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
fig, ax = plt.subplots()
radii = [1, 2, 3, 4, 5]
angle = np.linspace(0, 2 * np.pi, 150)
cmap = plt.get_cmap('viridis_r')
norm = plt.Normalize(radii[0], radii[-1])
m = plt.cm.ScalarMappable(cmap=cmap)
m.set_array(radii)
for radius in radii:
x = radius * np.cos(angle)
y = radius * np.sin(angle)
ax.plot(x, y, color=cmap(norm(radius)))
# Set box that will act as a 'fake' legend, 25% width of the
# x-axis, 15% of y-axis
cbbox = inset_axes(ax, width="25%", height="15%", loc=2)
cbbox.tick_params(
axis = 'both',
left = False,
top = False,
right = False,
bottom = False,
labelleft = False,
labeltop = False,
labelright = False,
labelbottom = False
)
# Semi-transparent like the usual ax.legend()
cbbox.set_facecolor([1, 1, 1, 0.7])
# Colorbar inside the fake legend box, occupying 85% of the
# box width and %5 box height
cbaxes = inset_axes(cbbox, width="85%", height="5%", loc=2)
cbar = fig.colorbar(m, cax=cbaxes, orientation='horizontal',
ticks=[1, 3, 5])
cbar.set_label('Radius', size=9)
cbar.ax.tick_params(labelsize=9)
ax.set_aspect(1)
plt.show()
I was unsuccessful in creating an actual ax.legend() from a LineCollection or a multicolored line - it only plotted one color - so my solution was this 'fake' legend approach. Hope this helps, cheers.
How can I configure plt.plot such that overlapped lines will have darker colors?
For example, I would like to use plt.plot to display the samples in such a way that the density that can be seen in the upper plot will be clear in the lower plot.
From the lower plot it's hard to understand where most of the samples are located
Here is the code I used in order to generate the example:
import numpy as np
import matplotlib.pyplot as plt
time = 100
n_samples = 7000
x = np.linspace(0, time, n_samples)
r1 = np.random.normal(0, 1, x.size)
r2 = np.random.uniform(-6, 6, x.size)
data = np.dstack((r1, r2)).flatten()
fig, axs = plt.subplots(2, 1, figsize=(9, 6))
axs[0].scatter(np.arange(len(data)), data, alpha=0.1)
axs[1].plot(np.arange(len(data)), data, alpha=0.2)
plt.show()
Update: segmentation and plotting into separated function
Instead of drawing one large curve, you could create each line segment separately and then draw these. That way, the overlapping segments will be blended via the transparency.
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
import numpy as np
def plot_line_as_segments(xs, ys=None, ax=None, **kwargs):
ax = ax or plt.gca()
if ys is None:
ys = xs
xs = np.arange(len(ys))
segments = np.c_[xs[:-1], ys[:-1], xs[1:], ys[1:]].reshape(-1, 2, 2)
added_collection = ax.add_collection(LineCollection(segments, **kwargs))
ax.autoscale()
return added_collection
time = 100
n_samples = 7000
x = np.linspace(0, time, n_samples)
r1 = np.random.normal(0, 1, x.size)
r2 = np.random.uniform(-6, 6, x.size)
data = np.dstack((r1, r2)).flatten()
fig, axs = plt.subplots(2, 1, figsize=(9, 6))
axs[0].scatter(np.arange(len(data)), data, alpha=0.1)
axs[0].margins(x=0)
plot_line_as_segments(data, ax=axs[1], alpha=0.05)
axs[1].margins(x=0)
plt.show()
I am running into a problem with pcolor() from matplotlib. I want to plot patches which have a quadrilateral shape. (They do have a non regular shape, but do have 4 corners and are not overlapping).
To demonstrate my problem, here is a minimal code which produces unexpected behavior.
import numpy as np
from matplotlib import pyplot as plt
x = [0, 1]
y = [0, 2]
val = [[1]]
xx, yy = np.meshgrid(x, y)
fig, ax = plt.subplots(1, 2, figsize=[10, 10])
ax = plt.subplot(2, 1, 1)
yy[1,0] =2.9
#displays a 1x2 rectangle
ax.pcolor(xx, yy, val, edgecolors='black')
ax = plt.subplot(2, 1, 2)
yy[1,0] =3
#displays the expected 1x3(x2) trapezoid
ax.pcolor(xx, yy, val, edgecolors='black')
plt.show()
(We are expecting a trapezoid with height 2.9 but it outputs a rectangle with 2x1. The second example with height 3 works fine)
Here is the output
Also, using pcolormesh, the same problem occurs.
Is this a bug or am I just blind?
The problem is the data type of xx and yy is int64. So when you attempt the assignment yy[1, 0] = 2.9 it is cast to an int, resulting in yy[1, 0] == 2.
The solution is to change the datatype to float, simplest way to do that is using numpy.ndarray.astype:
import numpy as np
from matplotlib import pyplot as plt
x = [0, 1]
y = [0, 2]
val = [[1]]
xx, yy = np.meshgrid(x, y)
xx = xx.astype('float64')
yy = yy.astype('float64')
fig, ax = plt.subplots(1, 2, figsize=[10, 10])
ax = plt.subplot(2, 1, 1)
yy[1,0] = 2.9
ax.pcolor(xx, yy, val, edgecolors='black')
ax = plt.subplot(2, 1, 2)
yy[1,0] = 3
ax.pcolor(xx, yy, val, edgecolors='black')
This will give the expected result
I want to start the curve with one color and progressively blend into another color until the end. The following function in my MCVE works, but surely, there has to be a better way I haven't found out about, yet?!
import numpy as np
import matplotlib.pyplot as plt
def colorlist(color1, color2, num):
"""Generate list of num colors blending from color1 to color2"""
result = [np.array(color1), np.array(color2)]
while len(result) < num:
temp = [result[0]]
for i in range(len(result)-1):
temp.append(np.sqrt((result[i]**2+result[i+1]**2)/2))
temp.append(result[i+1])
result = temp
indices = np.linspace(0, len(result)-1, num).round().astype(int)
return [result[i] for i in indices]
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
colors = colorlist((1, 0, 0), (0, 0, 1), len(x))
for i in range(len(x)-1):
xi = x[i:i+1+1]
yi = y[i:i+1+1]
ci = colors[i]
plt.plot(xi, yi, color=ci, linestyle='solid', linewidth='10')
plt.show()
Not sure what "better way" refers to. A solution with less code, which would draw faster is the use of a LineCollection together with a colormap.
A colormap can be defined by two colors and any colors in between are automatically interpolated.
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", [(1, 0, 0), (0, 0, 1)])
A LineCollection can be used to plot a lot of lines at once. Being a ScalarMappable it can use a colormap to colorize each line differently according to some array - in this case one may just use the x values for that purpose.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import LinearSegmentedColormap
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
cmap = LinearSegmentedColormap.from_list("", [(1, 0, 0), (0, 0, 1)])
points = np.array([x, y]).T.reshape(-1,1,2)
segments = np.concatenate([points[:-1],points[1:]], axis=1)
lc = LineCollection(segments, cmap=cmap, linewidth=10)
lc.set_array(x)
plt.gca().add_collection(lc)
plt.gca().autoscale()
plt.show()
The drawback of this solution as can be see in the picture is that the individual lines are not well connected.
So to circumvent this, one may plot those points overlapping, using
segments = np.concatenate([points[:-2],points[1:-1], points[2:]], axis=1)
In the above the color is linearly interpolated between the two given colors. The plot therefore looks different than the one from the question using some custom interpolation.
To obtain the same colors as in the question, you may use the same function to create the colors used in the colormap for the LineCollection. If the aim is to simplify this function you may directly calculate the values as the square root of the color difference in the channels.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import LinearSegmentedColormap
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
def colorlist2(c1, c2, num):
l = np.linspace(0,1,num)
a = np.abs(np.array(c1)-np.array(c2))
m = np.min([c1,c2], axis=0)
s = np.sign(np.array(c2)-np.array(c1)).astype(int)
s[s==0] =1
r = np.sqrt(np.c_[(l*a[0]+m[0])[::s[0]],(l*a[1]+m[1])[::s[1]],(l*a[2]+m[2])[::s[2]]])
return r
cmap = LinearSegmentedColormap.from_list("", colorlist2((1, 0, 0), (0, 0, 1),100))
points = np.array([x, y]).T.reshape(-1,1,2)
segments = np.concatenate([points[:-2],points[1:-1], points[2:]], axis=1)
lc = LineCollection(segments, cmap=cmap, linewidth=10)
lc.set_array(x)
plt.gca().add_collection(lc)
plt.gca().autoscale()
plt.show()
In response to a comment above: If you want to change the color depending on the y value, you can use the following code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import LinearSegmentedColormap
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)
ynorm = (y - y.min()) / (y.max() - y.min())
def colorlist2(c1, c2, num):
l = np.linspace(0, 1, num)
a = np.abs(np.array(c1) - np.array(c2))
m = np.min([c1, c2], axis=0)
s = np.sign(np.array(c2) - np.array(c1)).astype(int)
s[s == 0] = 1
r = np.sqrt(np.c_[(l * a[0] + m[0])[::s[0]],
(l * a[1] + m[1])[::s[1]], (l * a[2] + m[2])[::s[2]]])
return r
cmap = LinearSegmentedColormap.from_list(
"", colorlist2((1, 0, 0), (0, 0, 1), 100))
colors = [cmap(k) for k in ynorm[:-1]]
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-2], points[1:-1], points[2:]], axis=1)
lc = LineCollection(segments, colors=colors, linewidth=10)
lc.set_array(x)
plt.gca().add_collection(lc)
plt.gca().autoscale()
plt.show()
This will output this graph:
Graph with color depending on y value
This is more of a general question about 3d histogram creation in python.
I have attempted to create a 3d histogram using the X and Y arrays in the following code
import matplotlib
import pylab
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D
from matplotlib import cm
def threedhist():
X = [1, 3, 5, 8, 6, 7, 1, 2, 4, 5]
Y = [3, 4, 3, 6, 5, 3, 1, 2, 3, 8]
fig = pylab.figure()
ax = Axes3D(fig)
ax.hist([X, Y], bins=10, range=[[0, 10], [0, 10]])
plt.xlabel('X')
plt.ylabel('Y')
plt.zlabel('Frequency')
plt.title('Histogram')
plt.show()
However, I am getting the following error
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
a3dhistogram()
File "C:/Users/ckiser/Desktop/Projects/Tom/Python Files/threedhistogram.py", line 24, in a3dhistogram
ax.hist([X, Y], bins=10, range=[[0, 10], [0, 10]])
File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 7668, in hist
m, bins = np.histogram(x[i], bins, weights=w[i], **hist_kwargs)
File "C:\Python27\lib\site-packages\numpy\lib\function_base.py", line 169, in histogram
mn, mx = [mi+0.0 for mi in range]
TypeError: can only concatenate list (not "float") to list
I have tried the code with and without the "[" in the line
ax.hist([X, Y], bins=10, range=[[0, 10], [0, 10]])
I have also tried the function from numpy without success
H, xedges, yedges = np.histogram2d(x, y, bins = (10, 10))
Am I missing a step or a parameter? Any advice would be greatly appreciated.
I posted this in a related thread about colored 3d bar plots, but I think it's also relevant here as I couldn't find a complete answer for what I needed in either thread. This code generates a histogram scatterplot for any sort of x-y data. The height represents the frequency of values in that bin. So, for example, if you had many data point where (x,y) = (20,20) it would be high and red. If you had few data points in the bin where (x,y) = (100,100) it would be low and blue.
Note: result will vary substantially depending on how much data you have and how many bins your choose for you histogram. Adjust accordingly!
xAmplitudes = #your data here
yAmplitudes = #your other data here
x = np.array(xAmplitudes) #turn x,y data into numpy arrays
y = np.array(yAmplitudes)
fig = plt.figure() #create a canvas, tell matplotlib it's 3d
ax = fig.add_subplot(111, projection='3d')
#make histogram stuff - set bins - I choose 20x20 because I have a lot of data
hist, xedges, yedges = np.histogram2d(x, y, bins=(20,20))
xpos, ypos = np.meshgrid(xedges[:-1]+xedges[1:], yedges[:-1]+yedges[1:])
xpos = xpos.flatten()/2.
ypos = ypos.flatten()/2.
zpos = np.zeros_like (xpos)
dx = xedges [1] - xedges [0]
dy = yedges [1] - yedges [0]
dz = hist.flatten()
cmap = cm.get_cmap('jet') # Get desired colormap - you can change this!
max_height = np.max(dz) # get range of colorbars so we can normalize
min_height = np.min(dz)
# scale each z to [0,1], and get their rgb values
rgba = [cmap((k-min_height)/max_height) for k in dz]
ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color=rgba, zsort='average')
plt.title("X vs. Y Amplitudes for ____ Data")
plt.xlabel("My X data source")
plt.ylabel("My Y data source")
plt.savefig("Your_title_goes_here")
plt.show()
The results for about 75k data points of mine are below. Note, you can drag and drop to different perspectives and may want to save multiple views for presentations, posterity.
Have a look at
https://matplotlib.org/stable/gallery/mplot3d/hist3d.html, this has a working example script.
I've improved the code at that link to be more of a histogram:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = [1, 3, 5, 8, 6, 7, 1, 2, 4, 5]
y = [3, 4, 3, 6, 5, 3, 1, 2, 3, 8]
hist, xedges, yedges = np.histogram2d(x, y, bins=(4,4))
xpos, ypos = np.meshgrid(xedges[:-1]+xedges[1:], yedges[:-1]+yedges[1:])
xpos = xpos.flatten()/2.
ypos = ypos.flatten()/2.
zpos = np.zeros_like (xpos)
dx = xedges [1] - xedges [0]
dy = yedges [1] - yedges [0]
dz = hist.flatten()
ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b', zsort='average')
plt.xlabel ("X")
plt.ylabel ("Y")
plt.show()
I'm not sure how to do it with Axes3D.hist ().
In this answer there is a solution for 2D and 3D Histograms of scattered points. The usage is simple:
points, sub = hist2d_scatter( radius, density, bins=4 )
points, sub = hist3d_scatter( temperature, density, radius, bins=4 )
Where sub is a matplotlib "Subplot" instance (3D or not) and pointscontains the points used for the scatter plot.
I've added to #lxop's answer to allow for arbitrary size buckets:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = np.array([0, 2, 5, 10, 2, 3, 5, 2, 8, 10, 11])
y = np.array([0, 2, 5, 10, 6, 4, 2, 2, 5, 10, 11])
# This example actually counts the number of unique elements.
binsOne = sorted(set(x))
binsTwo = sorted(set(y))
# Just change binsOne and binsTwo to lists.
hist, xedges, yedges = np.histogram2d(x, y, bins=[binsOne, binsTwo])
# The start of each bucket.
xpos, ypos = np.meshgrid(xedges[:-1], yedges[:-1])
xpos = xpos.flatten()
ypos = ypos.flatten()
zpos = np.zeros_like(xpos)
# The width of each bucket.
dx, dy = np.meshgrid(xedges[1:] - xedges[:-1], yedges[1:] - yedges[:-1])
dx = dx.flatten()
dy = dy.flatten()
dz = hist.flatten()
ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b', zsort='average')