I want to annotate a horizontal bar chart I created with Pandas with '⭑' characters. The number of stars per bar is determined by a rating system that ranges from zero to five stars and contains half-star ratings. My issue is that there is no 1/2 star text character, so I have to use images which contain half-stars to properly annotate the bars.
Here is the code to create a sample from the DataFrame I am working from:
df = pd.DataFrame(index=range(7),
data={'Scores': [79.0, 79.5, 81.8, 76.1, 72.8, 87.6, 79.3]})
df['Stars'] = df['Scores'].apply(real_stars)
And here is the function that is determining the star ratings:
def real_stars(x):
if x >=88:
return ('★★★★★')
elif x >=83:
return ('★★★★¹/₂')
elif x >=79:
return ('★★★★')
elif x >=75:
return ('★★★¹/₂')
elif x >=71:
return ('★★★')
elif x >=67:
return ('★★¹/₂')
elif x >=63:
return ('★★')
elif x >=59:
return ('★¹/₂')
elif x >=55:
return ('★')
elif x >=50:
return ('¹/₂★')
else:
return None
And this is the code I use to plot the bar chart and annotate the right side of each bar with a star rating:
fig = plt.figure(figsize=(7.5,5))
ax = plt.subplot()
plt.box(on=None)
df.plot.barh(ax=ax, width=.75, legend=False)
for i, p in zip(df['Stars'], ax.patches):
width, height = p.get_width(), p.get_height()
x, y = p.get_xy()
ax.annotate(i, (p.get_x()+1*width, p.get_y()+.45*height), fontsize=25,
fontweight='bold', color='white', ha='right', va='center')
I would like to annotate the bars the exact same way, but instead of expressing a half star rating as '1/2', I would instead like to include an image of a half star. I think the first step would be to incorporate the images in the real_stars function, display the images in the df['Stars'] column and then use the column for annotation.
Examples of images I would like to use:
.5 star
1 star
Half star characters were added into unicode version 11, for example:
import matplotlib.pyplot as plt
import matplotlib.font_manager as mfm
font_path = '<PATH>/Symbola.ttf'
prop = mfm.FontProperties(fname=font_path) # find this font
# Some examples of stars
uni_char = u"\u2605\U0001F7CA\u2BE8\u2BEA"
plt.annotate(uni_char, (0.5, 0.5), fontproperties=prop, fontsize=20)
plt.show()
Please see this, and note that you have to use fonts that support the newer standard in this list. The example above uses Symbola
To annotate bars with shapes one may use an AnchoredOffsetbox, which contains a DrawingArea. The shapes inside the DrawingArea are defined in display space, relative to the Offsetbox.
import numpy as np
import matplotlib.markers
from matplotlib.path import Path
from matplotlib.patches import PathPatch
from matplotlib.offsetbox import AnchoredOffsetbox, DrawingArea
import matplotlib.pyplot as plt
class AnchoredDrawingArea(AnchoredOffsetbox):
def __init__(self, width, height, xdescent, ydescent,
loc, pad=0.4, borderpad=0.5, **kwargs):
self.da = DrawingArea(width, height, xdescent, ydescent)
super().__init__(loc, pad=pad, borderpad=borderpad,
child=self.da, **kwargs)
def get_star(pos=0, size=10, half=False, **kwargs):
marker = matplotlib.markers.MarkerStyle("*")
p = marker.get_path()
v = np.round(list(p.vertices[:]), 4)
c = np.array(list(p.codes[:]))
v *= size
v[:,0] += pos*2*size
if half:
v = np.delete(v, np.s_[6:-1],0)
c = np.delete(c, np.s_[6:-1],0)
return PathPatch(Path(v, c), **kwargs)
def draw_star(x,y,s, ax, size=10, **kwargs):
# https://matplotlib.org/gallery/misc/anchored_artists.html
ada = AnchoredDrawingArea(np.ceil(s)*2*size-size, size, size/2, size/2, loc="lower center",
bbox_to_anchor=(x,y,0,0), bbox_transform=ax.transData,
frameon=False)
for i in range(int(s)):
star = get_star(i, size=size, **kwargs)
ada.da.add_artist(star)
h = s - int(s)
if h > 0:
star = get_star(int(s), size=size, half=True, **kwargs)
ada.da.add_artist(star)
return ada
def draw_stars(x, y, s, ax=None, size=10, **kwargs):
ax = ax or plt.gca()
for xi,yi,si in zip(x,y,s):
ada = draw_star(xi,yi,si, ax=ax, size=size, **kwargs)
ax.add_artist(ada)
x = np.arange(6)
y = np.array([4,5,3,4,2,4])
stars = np.array([4, 2.5, 1, 3.5, 4.5, 2])
fig, ax = plt.subplots()
ax.bar(x,y)
draw_stars(x,y,stars, ax=ax, size=5, linewidth=0.72,
facecolor="crimson", edgecolor="darkred")
ax.margins(y=0.1)
plt.show()
Related
I'm having problems with heatmap.
I create the following function to show the analysis with heatmap
data = [ 0.00662896, -0.00213044, -0.00156812, 0.01450994, -0.00875174, -0.01561342, -0.00694762, 0.00476027, 0.00470659]
def plot_heatmap(pathOut, data, title, fileName, precis=2, show=False):
from matplotlib import cm
fig = plt.figure()
n = int(np.sqrt(len(data)))
data = data.reshape(n,n)
heatmap = plt.pcolor(data,cmap=cm.YlOrBr)
xLabels = (np.linspace(1,n,n,dtype=int))
yLabels = (np.linspace(1,n,n,dtype=int))
xpos = np.linspace(1,n,n)-0.5
ypos = np.linspace(1,n,n)-0.5
for y in range(n):
for x in range(n):
plt.text(x + 0.5, y + 0.5, f'{data[y, x]:.{precis}f}',
horizontalalignment='center',
verticalalignment='center',
)
plt.colorbar(heatmap, format='%.2f')
plt.xticks(xpos,xLabels)
plt.yticks(ypos,yLabels)
plt.title(f'{title}')
if (show == False ):
plt.close(fig)
elif (show == True):
plt.show()
fig.savefig(f'{pathOut}/{fileName}.pdf', format='pdf')
When I call the function the heatmap is created but not correctly, because I would like to show values at a specific precision. I know how to define text precision and scale precision, but how to adjust data precision to generate the correct heatmap?
In the attached figure, I have 7 cells equal to 0, for my desired precision, but the data used has a larger precision what produce different colors.
It is much easier to use seaborn.heatmap, which includes annotations and a colorbar. seaborn is a high-level API for matplotlib.
This significantly reduces the number of lines of code.
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
import seaborn as sns
def plot_heatmap(pathOut, fileName, data, title, precis=2, show=False):
n = int(np.sqrt(len(data)))
data = data.reshape(n, n)
xy_labels = range(1, n+1)
fig, ax = plt.subplots(figsize=(8, 6))
p = sns.heatmap(data=data, annot=True, fmt=f'.{precis}g', ax=ax,
cmap=cm.YlOrBr, xticklabels=xy_labels, yticklabels=xy_labels)
ax.invert_yaxis() # invert the axis if desired
ax.set_title(f'{title}')
fig.savefig(f'{pathOut}/{fileName}.pdf', format='pdf')
if (show == False ):
plt.close(fig)
elif (show == True):
plt.show()
data = np.array([ 0.00662896, -0.00213044, -0.00156812, 0.01450994, -0.00875174, -0.01561342, -0.00694762, 0.00476027, 0.00470659])
plot_heatmap('.', 'test', data, 'test', 4, True)
The f-string for plt.txt is not correct. It will be easier to round the value and convert it to a str type.
str(round(data[x, y], precis)) instead of f'{data[y, x]:.{precis}f}'
data[x, y] should be data[y, x]
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
def plot_heatmap(pathOut, fileName, data, title, precis=2, show=False):
fig = plt.figure(figsize=(8, 6))
n = int(np.sqrt(len(data)))
data = data.reshape(n, n)
heatmap = plt.pcolor(data, cmap=cm.YlOrBr)
xLabels = (np.linspace(1,n,n,dtype=int))
yLabels = (np.linspace(1,n,n,dtype=int))
xpos = np.linspace(1,n,n)-0.5
ypos = np.linspace(1,n,n)-0.5
for y in range(n):
for x in range(n):
s = str(round(data[y, x], precis)) # added s for plt.txt and reverse x and y for data addressing
plt.text(x + 0.5, y + 0.5, s,
horizontalalignment='center',
verticalalignment='center',
)
plt.colorbar(heatmap, format=f'%.{precis}f') # add precis to the colorbar
plt.xticks(xpos,xLabels)
plt.yticks(ypos,yLabels)
plt.title(f'{title}')
fig.savefig(f'{pathOut}/{fileName}.pdf', format='pdf') # this should be before plt.show()
if (show == False ):
plt.close(fig)
elif (show == True):
plt.show()
# the function expects an array, not a list
data = np.array([ 0.00662896, -0.00213044, -0.00156812, 0.01450994, -0.00875174, -0.01561342, -0.00694762, 0.00476027, 0.00470659])
# function call
plot_heatmap('.', 'test', data, 'test', 4, True)
I'd like to add an arrow to a line plot with matplotlib like in the plot below (drawn with pgfplots).
How can I do (position and direction of the arrow should be parameters ideally)?
Here is some code to experiment.
from matplotlib import pyplot
import numpy as np
t = np.linspace(-2, 2, 100)
plt.plot(t, np.sin(t))
plt.show()
Thanks.
In my experience this works best by using annotate. Thereby you avoid the weird warping you get with ax.arrow which is somehow hard to control.
EDIT: I've wrapped it into a little function.
from matplotlib import pyplot as plt
import numpy as np
def add_arrow(line, position=None, direction='right', size=15, color=None):
"""
add an arrow to a line.
line: Line2D object
position: x-position of the arrow. If None, mean of xdata is taken
direction: 'left' or 'right'
size: size of the arrow in fontsize points
color: if None, line color is taken.
"""
if color is None:
color = line.get_color()
xdata = line.get_xdata()
ydata = line.get_ydata()
if position is None:
position = xdata.mean()
# find closest index
start_ind = np.argmin(np.absolute(xdata - position))
if direction == 'right':
end_ind = start_ind + 1
else:
end_ind = start_ind - 1
line.axes.annotate('',
xytext=(xdata[start_ind], ydata[start_ind]),
xy=(xdata[end_ind], ydata[end_ind]),
arrowprops=dict(arrowstyle="->", color=color),
size=size
)
t = np.linspace(-2, 2, 100)
y = np.sin(t)
# return the handle of the line
line = plt.plot(t, y)[0]
add_arrow(line)
plt.show()
It's not very intuitive but it works. You can then fiddle with the arrowprops dictionary until it looks right.
Just add a plt.arrow():
from matplotlib import pyplot as plt
import numpy as np
# your function
def f(t): return np.sin(t)
t = np.linspace(-2, 2, 100)
plt.plot(t, f(t))
plt.arrow(0, f(0), 0.01, f(0.01)-f(0), shape='full', lw=0, length_includes_head=True, head_width=.05)
plt.show()
EDIT: Changed parameters of arrow to include position & direction of function to draw.
Not the nicest solution, but should work:
import matplotlib.pyplot as plt
import numpy as np
def makeArrow(ax,pos,function,direction):
delta = 0.0001 if direction >= 0 else -0.0001
ax.arrow(pos,function(pos),pos+delta,function(pos+delta),head_width=0.05,head_length=0.1)
fun = np.sin
t = np.linspace(-2, 2, 100)
ax = plt.axes()
ax.plot(t, fun(t))
makeArrow(ax,0,fun,+1)
plt.show()
I know this doesn't exactly answer the question as asked, but I thought this could be useful to other people landing here. I wanted to include the arrow in my plot's legend, but the solutions here don't mention how. There may be an easier way to do this, but here is my solution:
To include the arrow in your legend, you need to make a custom patch handler and use the matplotlib.patches.FancyArrow object. Here is a minimal working solution. This solution piggybacks off of the existing solutions in this thread.
First, the imports...
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerPatch
import matplotlib.patches as patches
from matplotlib.lines import Line2D
import numpy as np
Now, we make a custom legend handler. This handler can create legend artists for any line-patch combination, granted that the line has no markers.
class HandlerLinePatch(HandlerPatch):
def __init__(self, linehandle=None, **kw):
HandlerPatch.__init__(self, **kw)
self.linehandle=linehandle
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width,
height, fontsize, trans):
p = super().create_artists(legend, orig_handle,
xdescent, descent,
width, height, fontsize,
trans)
line = Line2D([0,width],[height/2.,height/2.])
if self.linehandle is None:
line.set_linestyle('-')
line._color = orig_handle._edgecolor
else:
self.update_prop(line, self.linehandle, legend)
line.set_drawstyle('default')
line.set_marker('')
line.set_transform(trans)
return [p[0],line]
Next, we write a function that specifies the type of patch we want to include in the legend - an arrow in our case. This is courtesy of Javier's answer here.
def make_legend_arrow(legend, orig_handle,
xdescent, ydescent,
width, height, fontsize):
p = patches.FancyArrow(width/2., height/2., width/5., 0,
length_includes_head=True, width=0,
head_width=height, head_length=height,
overhang=0.2)
return p
Next, a modified version of the add_arrow function from Thomas' answer that uses the FancyArrow patch rather than annotations. This solution might cause weird wrapping like Thomas warned against, but I couldn't figure out how to put the arrow in the legend if the arrow is an annotation.
def add_arrow(line, ax, position=None, direction='right', color=None, label=''):
"""
add an arrow to a line.
line: Line2D object
position: x-position of the arrow. If None, mean of xdata is taken
direction: 'left' or 'right'
color: if None, line color is taken.
label: label for arrow
"""
if color is None:
color = line.get_color()
xdata = line.get_xdata()
ydata = line.get_ydata()
if position is None:
position = xdata.mean()
# find closest index
start_ind = np.argmin(np.absolute(xdata - position))
if direction == 'right':
end_ind = start_ind + 1
else:
end_ind = start_ind - 1
dx = xdata[end_ind] - xdata[start_ind]
dy = ydata[end_ind] - ydata[start_ind]
size = abs(dx) * 5.
x = xdata[start_ind] + (np.sign(dx) * size/2.)
y = ydata[start_ind] + (np.sign(dy) * size/2.)
arrow = patches.FancyArrow(x, y, dx, dy, color=color, width=0,
head_width=size, head_length=size,
label=label,length_includes_head=True,
overhang=0.3, zorder=10)
ax.add_patch(arrow)
Now, a helper function to plot both the arrow and the line. It returns a Line2D object, which is needed for the legend handler we wrote in the first code block
def plot_line_with_arrow(x,y,ax=None,label='',**kw):
if ax is None:
ax = plt.gca()
line = ax.plot(x,y,**kw)[0]
add_arrow(line, ax, label=label)
return line
Finally, we make the plot and update the legend's handler_map with our custom handler.
t = np.linspace(-2, 2, 100)
y = np.sin(t)
line = plot_line_with_arrow(t,y,label='Path', linestyle=':')
plt.gca().set_aspect('equal')
plt.legend(handler_map={patches.FancyArrow :
HandlerLinePatch(patch_func=make_legend_arrow,
linehandle=line)})
plt.show()
Here is the output:
I've found that quiver() works better than arrow() or annotate() when the x and y axes have very different scales. Here's my helper function for plotting a line with arrows:
def plot_with_arrows(ax, x, y, color="g", label="", n_arrows=2):
ax.plot(x, y, rasterized=True, color=color, label=label)
x_range = x.max() - x.min()
y_range = y.max() - y.min()
for i in np.linspace(x.keys().min(), x.keys().max(), n_arrows * 2 + 1).astype(np.int32)[1::2]:
direction = np.array([(x[i+5] - x[i]), (y[i+5] - y[i])])
direction = direction / (np.sqrt(np.sum(np.power(direction, 2)))) * 0.05
direction[0] /= x_range
direction[1] /= y_range
ax.quiver(x[i], y[i], direction[0], direction[1], color=color)
I am trying to draw a series of lines. The lines are all the same length, and randomly switch colors for a random length (blue to orange). I am drawing the lines in blue and then overlaying orange on top. You can see from my picture there are clipped parts of the lines where it is grey. I cannot figure out why this is happening. Also related I believe is that my labels are not moving to a left alignment like they should. Any help is greatly appreciated.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
import random
plt.close('all')
fig, ax = plt.subplots(figsize=(15,11))
def label(xy, text):
y = xy[1] - 2
ax.text(xy[0], y, text, ha="left", family='sans-serif', size=14)
def draw_chromosome(start, stop, y, color):
x = np.array([start, stop])
y = np.array([y, y])
line = mlines.Line2D(x , y, lw=10., color=color)
ax.add_line(line)
x = 50
y = 100
chr = 1
for i in range(22):
draw_chromosome(x, 120, y, "#1C2F4D")
j = 0
while j < 120:
print j
length = 1
if random.randint(1, 100) > 90:
length = random.randint(1, 120-j)
draw_chromosome(j, j+length, y, "#FA9B00")
j = j+length+1
label([x, y], "Chromosome%i" % chr)
y -= 3
chr += 1
plt.axis('equal')
plt.axis('off')
plt.tight_layout()
plt.show()
You're only drawing the blue background from x = 50 to x = 120.
Replace this line:
draw_chromosome(x, 120, y, "#1C2F4D")
with this:
draw_chromosome(0, 120, y, "#1C2F4D")
To draw the blue line all the way across.
Alternately, if you also want to move your labels to the left, you can just set x=0 instead of setting it to 50.
I suggest using LineCollection for this. Below is a little helper function I wrote based on the example at http://matplotlib.org/examples/pylab_examples/multicolored_line.html (it looks long, but there is a lot of comments + docstrings)
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm
from matplotlib.ticker import NullLocator
from collections import OrderedDict
def binary_state_lines(ax, chrom_data, xmin=0, xmax=120,
delta_y=3,
off_color = "#1C2F4D",
on_color = "#FA9B00"):
"""
Draw a whole bunch of chromosomes
Parameters
----------
ax : Axes
The axes to draw stuff to
chrom_data : OrderedDict
The chromosome data as a dict, key on the label with a list of pairs
of where the data is 'on'. Data is plotted top-down
xmin, xmax : float, optional
The minimum and maximum limits for the x values
delta_y : float, optional
The spacing between lines
off_color, on_color : color, optional
The colors to use for the the on/off state
Returns
-------
collections : dict
dictionary of the collections added keyed on the label
"""
# base offset
y_val = 0
# make the color map and norm
cmap = ListedColormap([off_color, on_color])
norm = BoundaryNorm([0, 0.5, 1], cmap.N)
# sort out where the text should be
txt_x = (xmax + xmin) / 2
# dictionary to hold the returned artists
ret = dict()
# loop over the input data draw each collection
for label, data in chrom_data.items():
# increment the y offset
y_val += delta_y
# turn the high windows on to alternating
# high/low regions
x = np.asarray(data).ravel()
# assign the high/low state to each one
state = np.mod(1 + np.arange(len(x)), 2)
# deal with boundary conditions to be off
# at start/end
if x[0] > xmin:
x = np.r_[xmin, x]
state = np.r_[0, state]
if x[-1] < xmax:
x = np.r_[x, xmax]
state = np.r_[state, 0]
# make the matching y values
y = np.ones(len(x)) * y_val
# call helper function to create the collection
coll = draw_segments(ax, x, y, state,
cmap, norm)
ret[label] = coll
# set up the axes limits
ax.set_xlim(xmin, xmax)
ax.set_ylim(0, y_val + delta_y)
# turn off x-ticks
ax.xaxis.set_major_locator(NullLocator())
# make the y-ticks be labeled as per the input
ax.yaxis.set_ticks((1 + np.arange(len(chrom_data))) * delta_y)
ax.yaxis.set_ticklabels(list(chrom_data.keys()))
# invert so that the first data is at the top
ax.invert_yaxis()
# turn off the frame and patch
ax.set_frame_on(False)
# return the added artists
return ret
def draw_segments(ax, x, y, state, cmap, norm, lw=10):
"""
helper function to turn boundary edges into the input LineCollection
expects.
Parameters
----------
ax : Axes
The axes to draw to
x, y, state : array
The x edges, the y values and the state of each region
cmap : matplotlib.colors.Colormap
The color map to use
norm : matplotlib.ticker.Norm
The norm to use with the color map
lw : float, optional
The width of the lines
"""
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
lc = LineCollection(segments, cmap=cmap, norm=norm)
lc.set_array(state)
lc.set_linewidth(lw)
ax.add_collection(lc)
return lc
An example:
synthetic_data = OrderedDict()
for j in range(21):
key = 'data {:02d}'.format(j)
synthetic_data[key] = np.cumsum(np.random.randint(1, 10, 20)).reshape(-1, 2)
fig, ax = plt.subplots(tight_layout=True)
binary_state_lines(ax, synthetic_data, xmax=120)
plt.show()
Separating the plotting logic from everything else will make your code easier to maintain and more reusable.
I also took the liberty of moving your labels from between the lines (where they can be ambiguous) to the yaxis tick labels.
I was wondering if it is possible to plot a curve in matplotlib with arrow ticks.
Something like:
from pylab import *
y = linspace(0,10,0.01)
x = cos(y)
plot(x, y, '->')
which should come out with a curve made like this --->---->----> when x increases and like this ---<----<----< whenit decreases (and for y as well, of course).
EDIT:
Furthermore, the arrows should be inclined in the curve's direction (for example, 45 degrees for the y=x function)
It is possible to use the same strategy as in matplotlib streamplot function. Based on the example already given by hitzg:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
import matplotlib.patches as mpatches
def add_arrow_to_line2D(
axes, line, arrow_locs=[0.2, 0.4, 0.6, 0.8],
arrowstyle='-|>', arrowsize=1, transform=None):
"""
Add arrows to a matplotlib.lines.Line2D at selected locations.
Parameters:
-----------
axes:
line: Line2D object as returned by plot command
arrow_locs: list of locations where to insert arrows, % of total length
arrowstyle: style of the arrow
arrowsize: size of the arrow
transform: a matplotlib transform instance, default to data coordinates
Returns:
--------
arrows: list of arrows
"""
if not isinstance(line, mlines.Line2D):
raise ValueError("expected a matplotlib.lines.Line2D object")
x, y = line.get_xdata(), line.get_ydata()
arrow_kw = {
"arrowstyle": arrowstyle,
"mutation_scale": 10 * arrowsize,
}
color = line.get_color()
use_multicolor_lines = isinstance(color, np.ndarray)
if use_multicolor_lines:
raise NotImplementedError("multicolor lines not supported")
else:
arrow_kw['color'] = color
linewidth = line.get_linewidth()
if isinstance(linewidth, np.ndarray):
raise NotImplementedError("multiwidth lines not supported")
else:
arrow_kw['linewidth'] = linewidth
if transform is None:
transform = axes.transData
arrows = []
for loc in arrow_locs:
s = np.cumsum(np.sqrt(np.diff(x) ** 2 + np.diff(y) ** 2))
n = np.searchsorted(s, s[-1] * loc)
arrow_tail = (x[n], y[n])
arrow_head = (np.mean(x[n:n + 2]), np.mean(y[n:n + 2]))
p = mpatches.FancyArrowPatch(
arrow_tail, arrow_head, transform=transform,
**arrow_kw)
axes.add_patch(p)
arrows.append(p)
return arrows
y = np.linspace(0, 100, 200)
x = np.cos(y/5.)
fig, ax = plt.subplots(1, 1)
# print the line and the markers in seperate steps
line, = ax.plot(x, y, 'k-')
add_arrow_to_line2D(ax, line, arrow_locs=np.linspace(0., 1., 200),
arrowstyle='->')
plt.show()
Also refer to this answer.
Try this:
import numpy as np
import matplotlib.pyplot as plt
y = np.linspace(0,100,100)
x = np.cos(y/5.)
# use masked arrays
x1 = np.ma.masked_array(x[:-1], np.diff(x)>=0)
x2 = np.ma.masked_array(x[:-1], np.diff(x)<=0)
# print the line and the markers in seperate steps
plt.plot(x, y, 'k-')
plt.plot(x1, y[:-1], 'k<')
plt.plot(x2, y[:-1], 'k>')
plt.show()
In this example the color is correlative to the radius of each bar. How would one add a colorbar to this plot?
My code mimics a "rose diagram" projection which is essentially a bar chart on a polar projection.
here is a part of it:
angle = radians(10.)
patches = radians(360.)/angle
theta = np.arange(0,radians(360.),angle)
count = [0]*patches
for i, item in enumerate(some_array_of_azimuth_directions):
temp = int((item - item%angle)/angle)
count[temp] += 1
width = angle * np.ones(patches)
# force square figure and square axes looks better for polar, IMO
fig = plt.figure(figsize=(8,8))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True)
rmax = max(count) + 1
ax.set_rlim(0,rmax)
ax.set_theta_offset(np.pi/2)
ax.set_thetagrids(np.arange(0,360,10))
ax.set_theta_direction(-1)
# project strike distribution as histogram bars
bars = ax.bar(theta, count, width=width)
r_values = []
colors = []
for r,bar in zip(count, bars):
r_values.append(r/float(max(count)))
colors.append(cm.jet(r_values[-1], alpha=0.5))
bar.set_facecolor(colors[-1])
bar.set_edgecolor('grey')
bar.set_alpha(0.5)
# Add colorbar, make sure to specify tick locations to match desired ticklabels
colorlist = []
r_values.sort()
values = []
for val in r_values:
if val not in values:
values.append(val*float(max(count)))
color = cm.jet(val, alpha=0.5)
if color not in colorlist:
colorlist.append(color)
cpt = mpl.colors.ListedColormap(colorlist)
bounds = range(max(count)+1)
norm = mpl.colors.BoundaryNorm(values, cpt.N-1)
cax = fig.add_axes([0.97, 0.3, 0.03, 0.4])
cb = mpl.colorbar.ColorbarBase(cax, cmap=cpt,
norm=norm,
boundaries=bounds,
# Make the length of each extension
# the same as the length of the
# interior colors:
extendfrac='auto',
ticks=[bounds[i] for i in range(0, len(bounds), 2)],
#ticks=bounds,
spacing='uniform')
and here is the resulting plot:
As you can see, the colorbar is not quite right. If you look closely, between 16 and 17, there is a color missing (darker orange) and according to the colorbar the yellows reach a value of 15, which is not true in the rose diagram (or the data).
I have played around with the code so much and I just can't figure out how to normalize the colorbar correctly.
The easiest way is to use a PatchCollection and pass in your "z" (i.e. the values you want to color by) as the array kwarg.
As a simple example:
import itertools
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from matplotlib.collections import PatchCollection
import numpy as np
def main():
fig = plt.figure()
ax = fig.add_subplot(111, projection='polar')
x = np.radians(np.arange(0, 360, 10))
y = np.random.random(x.size)
z = np.random.random(y.size)
cmap = plt.get_cmap('cool')
coll = colored_bar(x, y, z, ax=ax, width=np.radians(10), cmap=cmap)
fig.colorbar(coll)
ax.set_yticks([0.5, 1.0])
plt.show()
def colored_bar(left, height, z=None, width=0.8, bottom=0, ax=None, **kwargs):
if ax is None:
ax = plt.gca()
width = itertools.cycle(np.atleast_1d(width))
bottom = itertools.cycle(np.atleast_1d(bottom))
rects = []
for x, y, w, h in zip(left, bottom, width, height):
rects.append(Rectangle((x,y), w, h))
coll = PatchCollection(rects, array=z, **kwargs)
ax.add_collection(coll)
ax.autoscale()
return coll
if __name__ == '__main__':
main()
If you want a discrete color map, it's easiest to just specify the number of intervals you'd like when you call plt.get_cmap. For example, in the code above, if you replace the line cmap = plt.get_cmap('cool') with:
cmap = plt.get_cmap('cool', 5)
Then you'll get a discrete colormap with 5 intervals. (Alternately, you could pass in the ListedColormap that you created in your example.)
If you want a "full-featured" rose diagram function, you might do something like this:
import itertools
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from matplotlib.collections import PatchCollection
import numpy as np
def main():
azi = np.random.normal(20, 30, 100)
z = np.cos(np.radians(azi + 45))
plt.figure(figsize=(5,6))
plt.subplot(111, projection='polar')
coll = rose(azi, z=z, bidirectional=True)
plt.xticks(np.radians(range(0, 360, 45)),
['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'])
plt.colorbar(coll, orientation='horizontal')
plt.xlabel('A rose diagram colored by a second variable')
plt.rgrids(range(5, 20, 5), angle=290)
plt.show()
def rose(azimuths, z=None, ax=None, bins=30, bidirectional=False,
color_by=np.mean, **kwargs):
"""Create a "rose" diagram (a.k.a. circular histogram).
Parameters:
-----------
azimuths: sequence of numbers
The observed azimuths in degrees.
z: sequence of numbers (optional)
A second, co-located variable to color the plotted rectangles by.
ax: a matplotlib Axes (optional)
The axes to plot on. Defaults to the current axes.
bins: int or sequence of numbers (optional)
The number of bins or a sequence of bin edges to use.
bidirectional: boolean (optional)
Whether or not to treat the observed azimuths as bi-directional
measurements (i.e. if True, 0 and 180 are identical).
color_by: function or string (optional)
A function to reduce the binned z values with. Alternately, if the
string "count" is passed in, the displayed bars will be colored by
their y-value (the number of azimuths measurements in that bin).
Additional keyword arguments are passed on to PatchCollection.
Returns:
--------
A matplotlib PatchCollection
"""
azimuths = np.asanyarray(azimuths)
if color_by == 'count':
z = np.ones_like(azimuths)
color_by = np.sum
if ax is None:
ax = plt.gca()
ax.set_theta_direction(-1)
ax.set_theta_offset(np.radians(90))
if bidirectional:
other = azimuths + 180
azimuths = np.concatenate([azimuths, other])
if z is not None:
z = np.concatenate([z, z])
# Convert to 0-360, in case negative or >360 azimuths are passed in.
azimuths[azimuths > 360] -= 360
azimuths[azimuths < 0] += 360
counts, edges = np.histogram(azimuths, range=[0, 360], bins=bins)
if z is not None:
idx = np.digitize(azimuths, edges)
z = np.array([color_by(z[idx == i]) for i in range(1, idx.max() + 1)])
z = np.ma.masked_invalid(z)
edges = np.radians(edges)
coll = colored_bar(edges[:-1], counts, z=z, width=np.diff(edges),
ax=ax, **kwargs)
return coll
def colored_bar(left, height, z=None, width=0.8, bottom=0, ax=None, **kwargs):
"""A bar plot colored by a scalar sequence."""
if ax is None:
ax = plt.gca()
width = itertools.cycle(np.atleast_1d(width))
bottom = itertools.cycle(np.atleast_1d(bottom))
rects = []
for x, y, h, w in zip(left, bottom, height, width):
rects.append(Rectangle((x,y), w, h))
coll = PatchCollection(rects, array=z, **kwargs)
ax.add_collection(coll)
ax.autoscale()
return coll
if __name__ == '__main__':
main()