Change matplotlib colorbar to custom height - python

I would like to set the colorbar of my plot to a custom height, not necessarily to match the size of the plot. In fact I would like the height of the colorbar PLUS the title on top of it to match the height of the figure.
With
ax3 = divider.append_axes('right', size='10%', pad=0.3)
cb = plt.colorbar(Q, cax=ax3, ticks=[0.0, 3.0, 6.0, 9.0, 12.0, 15.0], format='%.1f')
I managed to have a colorbar with the same height as the plot, which has been asked for many other times, now I would like to shrink it.
Following suggestion provided in other questions I decided to explicitly give the colorbar its own axes with add_axes, after getting the position of the last plot axes with get_position. Here is what I'm trying to do. There are no data and no colorbar in this example, just to show that I'm not getting the result I expected:
from __future__ import unicode_literals
import numpy as np
from scipy.interpolate import griddata
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib.pylab import cm
import matplotlib.colors as colors
from mpl_toolkits.axes_grid1 import make_axes_locatable, axes_size
matplotlib.rcParams.update({'font.size': 8})
fig = plt.figure()
fig.set_size_inches(6.3,6.3)
ax1 = plt.subplot(111)
divider = make_axes_locatable(ax1)
ax2 = divider.append_axes('right', size='100%', pad=0.3)
axes = [ax1, ax2]
ltypes = ['dashed', 'solid']
xi = np.linspace(-18.125, 18.125, 11)
yi = np.linspace(0, 28, 9)
xv, yv = np.meshgrid(xi, yi)
xcOdd = 0.2
zcOdd = 0.725
xcEven = 0.6
zcEven = 0.725
maskRadius = 0.15
for i in range(2):
ax = axes[i]
ax.set_xlabel('distance [m]')
if i == 0:
ax.set_ylabel('depth [m]')
if i == 1:
ax.set_yticklabels([])
ax.invert_yaxis()
ax.tick_params(direction='in')
ax.set_aspect('equal')
odd = Circle((xcOdd, zcOdd), .15, linewidth=1.2, color='k', fill=False)
even = Circle((xcEven, zcEven), .15, linewidth=1.2, linestyle=ltypes[i], color='k', fill=False)
vmax = 15.
vmin = 0.
norm = matplotlib.colors.Normalize(vmin,vmax, clip=False)
color_map = matplotlib.colors.ListedColormap(plt.cm.Greys(np.linspace(0.25, 1, 5)), "name")
ax.add_patch(odd)
pad = 0.03
width = 0.03
pos = ax2.get_position()
ax3 = fig.add_axes([pos.xmax + pad, pos.ymin, width, 0.7*(pos.ymax-pos.ymin) ])
plt.savefig('prova-vect-paper-test-2.eps', format='eps')
Why is get_position returning the wrong boundingbox?

You need to draw the canvas before obtaining the actual position from .get_position(). This is because due to the equal aspect ratio, the axes changes size and position at draw time.
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from mpl_toolkits.axes_grid1 import make_axes_locatable
matplotlib.rcParams.update({'font.size': 8})
fig = plt.figure()
fig.set_size_inches(6.3,6.3)
ax1 = plt.subplot(111)
divider = make_axes_locatable(ax1)
ax2 = divider.append_axes('right', size='100%', pad=0.3)
axes = [ax1, ax2]
xi = np.linspace(-18.125, 18.125, 11)
yi = np.linspace(0, 28, 9)
xv, yv = np.meshgrid(xi, yi)
for i in range(2):
ax = axes[i]
ax.set_xlabel('distance [m]')
if i == 0:
ax.set_ylabel('depth [m]')
if i == 1:
ax.set_yticklabels([])
ax.invert_yaxis()
ax.tick_params(direction='in')
ax.set_aspect('equal')
vmax = 15.
vmin = 0.
norm = colors.Normalize(vmin,vmax, clip=False)
color_map = colors.ListedColormap(plt.cm.Greys(np.linspace(0.25, 1, 5)), "name")
im = ax.imshow(yv, cmap=color_map, norm=norm)
pad = 0.03
width = 0.03
fig.canvas.draw()
pos = ax2.get_position()
ax3 = fig.add_axes([pos.xmax + pad, pos.ymin, width, 0.7*(pos.ymax-pos.ymin) ])
fig.colorbar(im, cax=ax3)
plt.show()

Related

matplotlib set_aspect(num) on an axis doesn't resize display box in a gridspec

I'm plotting an image with their two projections (x and y) in a GridSpec. When I use the set_aspect on the central image, the image size box isn't resized for its minimal size (without blank) as you can see below. Does somebody have a solution to resolve this case?
Matplotlib 3.0.2, Python 3.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
plt.rcParams['toolbar'] = 'toolmanager'
matplotlib.use('Qt5Agg')
ldata = np.random.random((256, 256))
xhisto = np.sum(ldata, axis=0)
yhisto = np.sum(ldata, axis=1)
fig = plt.figure()
gs = plt.GridSpec(2, 2, height_ratios=[10,1], width_ratios=[3,30], wspace=0.1, hspace=0.1)
ax_image = plt.subplot(gs[1])
ax_histoy = plt.subplot(gs[0], sharey=ax_image)
ax_histox = plt.subplot(gs[3], sharex=ax_image)
plt.subplots_adjust(right=0.8)
colorAx = plt.axes([0.85, 0.4, 0.02, 0.45])
im = ax_image.imshow(ldata, cmap='jet', interpolation='none', aspect='auto')
ax_histox.plot(xhisto)
ax_histoy.plot(yhisto, range(256))
ax_image.invert_yaxis()
ax_image.tick_params(labelbottom=False, labelleft=False)
ax_histoy.spines['right'].set_visible(False)
ax_histoy.spines['bottom'].set_visible(False)
ax_histox.spines['right'].set_visible(False)
ax_histox.spines['top'].set_visible(False)
ax_histoy.set_ylim(1,256)
ax_histox.set_xlim(1,256)
ax_histox.set_xlabel('X')
ax_histoy.set_ylabel('Y')
ax_image.set_title('Matplotlib - Plot 2D')
ax_histoy.tick_params(axis='x',labelsize=8,labelrotation=90)
ax_histox.tick_params(axis='y',labelsize=8)
ax_histoy.xaxis.tick_top()
ax_histox.yaxis.tick_left()
plt.colorbar(im, cax = colorAx)
ax_image.set_aspect(0.5)
plt.show()
I try to find a solution for resizing the height of the projection on the left
Using the example as you explain give the save result with a ratio different as 1:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
# Fixing random state for reproducibility
np.random.seed(19680801)
# the random data
x = np.random.randn(1000)
y = np.random.randn(1000)
fig, axScatter = plt.subplots(figsize=(5.5, 5.5))
# the scatter plot:
axScatter.scatter(x, y)
axScatter.set_aspect(0.3)
# create new axes on the right and on the top of the current axes
# The first argument of the new_vertical(new_horizontal) method is
# the height (width) of the axes to be created in inches.
divider = make_axes_locatable(axScatter)
axHistx = divider.append_axes("top", 1.2, pad=0.1, sharex=axScatter)
axHisty = divider.append_axes("right", 1.2, pad=0.1, sharey=axScatter)
# make some labels invisible
axHistx.xaxis.set_tick_params(labelbottom=False)
axHisty.yaxis.set_tick_params(labelleft=False)
# now determine nice limits by hand:
binwidth = 0.25
xymax = max(np.max(np.abs(x)), np.max(np.abs(y)))
lim = (int(xymax/binwidth) + 1)*binwidth
bins = np.arange(-lim, lim + binwidth, binwidth)
axHistx.hist(x, bins=bins)
axHisty.hist(y, bins=bins, orientation='horizontal')
# the xaxis of axHistx and yaxis of axHisty are shared with axScatter,
# thus there is no need to manually adjust the xlim and ylim of these
# axis.
axHistx.set_yticks([0, 50, 100])
axHisty.set_xticks([0, 50, 100])
plt.show()
Result with axes_grid
Could it solved with axes_grid ???

How to set discrete colorbar ticks in mpl_toolkits.axes_grid1.ImageGrid?

I want to set discrete colorbar in ImageGrid.
ImageGrid
Here's an example:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import numpy as np
import matplotlib
lon,lat = np.meshgrid(np.arange(-180, 180, 10), np.arange(-85, 90, 10))
data = np.sort(np.random.rand(18, 36),axis=1)
fig = plt.figure()
grid = ImageGrid(fig, 111,
nrows_ncols=(2, 1),
axes_pad=(0.35, 0.35),
label_mode="1",
share_all=True,
cbar_location="right",
cbar_mode="each",
cbar_size="5%",
cbar_pad="6%",
)
# Settings
bounds = [0,0.01,0.04,0.07,0.1,0.13,0.16,0.2,0.25,0.35,0.45,0.6,0.9]
colors = ['#390231','#7F1CAB','#0047FD','#0072FE','#019EFF','#00C4FF','#01EDFF',\
'#00FFFB','#00FFC8','#29F905','#FBDD03','#FA0F00']
# Original colorbar
p = grid[0].pcolormesh(lon,lat,data, vmin=0, vmax=0.9, cmap='jet')
cb = grid.cbar_axes[0].colorbar(p)
# Defined colorbar
cmap = matplotlib.colors.ListedColormap(colors)
norm = matplotlib.colors.BoundaryNorm(bounds, cmap.N)
p = grid[1].pcolormesh(lon,lat,data, cmap=cmap, norm=norm)
cb = grid.cbar_axes[1].colorbar(p, ticks=bounds)
grid[0].set_title('jet')
grid[1].set_title('Defined')
plt.show()
This is the result:
As you can see, the location of ticks are wrong.
If ticks are at boundaries of each color block, the second figure will look correct.
Subplots
Then, I tested subplots. It works fine!
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
lon,lat = np.meshgrid(np.arange(-180, 180, 10), np.arange(-85, 90, 10))
data = np.sort(np.random.rand(18, 36),axis=1)
f, (ax1, ax2) = plt.subplots(1, 2,sharey=True)
# Settings
bounds = [0,0.01,0.04,0.07,0.1,0.13,0.16,0.2,0.25,0.35,0.45,0.6,0.9]
colors = ['#390231','#7F1CAB','#0047FD','#0072FE','#019EFF','#00C4FF','#01EDFF',\
'#00FFFB','#00FFC8','#29F905','#FBDD03','#FA0F00']
# Defined colorbar
cmap = matplotlib.colors.ListedColormap(colors)
norm = matplotlib.colors.BoundaryNorm(bounds, cmap.N)
# Jet
p = ax1.pcolormesh(lon,lat,data, vmin=0, vmax=0.9, cmap='jet')
f.colorbar(p,ax=ax1)
ax1.set_title('jet')
# Defined
p = ax2.pcolormesh(lon,lat,data, cmap=cmap, norm=norm)
f.colorbar(p,ax=ax2,ticks=bounds)
ax2.set_title('defined')
plt.show()
This is the result:
Single
I tested my script in single figure. It works fine!
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
lon,lat = np.meshgrid(np.arange(-180, 180, 10), np.arange(-85, 90, 10))
data = np.sort(np.random.rand(18, 36),axis=1)
fig = plt.figure()
# Settings
bounds = [0,0.01,0.04,0.07,0.1,0.13,0.16,0.2,0.25,0.35,0.45,0.6,0.9]
colors = ['#390231','#7F1CAB','#0047FD','#0072FE','#019EFF','#00C4FF','#01EDFF',\
'#00FFFB','#00FFC8','#29F905','#FBDD03','#FA0F00']
# Defined colorbar
cmap = matplotlib.colors.ListedColormap(colors)
norm = matplotlib.colors.BoundaryNorm(bounds, cmap.N)
# Jet
plt.pcolormesh(lon,lat,data, vmin=0, vmax=0.9, cmap='jet')
plt.colorbar()
plt.show()
# Defined
p = plt.pcolormesh(lon,lat,data, cmap=cmap, norm=norm)
plt.colorbar(p, ticks=bounds)
plt.title('Single fig')
plt.show()
This is the result of single figure of jet and defined:
A workaround would be to set the labels manually.
ticks=np.linspace(bounds[0],bounds[-1], len(bounds))
cb = grid.cbar_axes[1].colorbar(p, ticks=ticks)
cb.ax.set_yticklabels(bounds)

How to make an animation over different values of n here?

I have written a code that plot some points and lines on the xy plane. It plots everything for a given value of n. So for different n I get my desired plots. But I want to animate these plots for different values of n, say, for n=1, 2, ..., 100. But I cannot do this animation.
Can anyone here help me to do this? Thank you.. I paste my code here:
My Code
import matplotlib as mpl
mpl.rc('text', usetex = True)
mpl.rc('font', family = 'serif')
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Circle
fig = plt.subplots()
ax = plt.axes(xlim=(-1.2, 1.2), ylim=(-1.2, 1.2))
plt.gca().set_aspect('equal', adjustable='box')
plt.style.use(['ggplot','dark_background'])
plt.rcParams['figure.figsize'] = (12, 8)
n = 10 #I want to animate this n.
p = 2
for k in range(0,n,1):
theta1 = np.pi + 2*k*np.pi / n
theta2 = np.pi + 2*p*k*np.pi / n
x, y = np.cos(theta1), np.sin(theta1)
x1, y1 = np.cos(theta2), np.sin(theta2)
plt.scatter(x, y, s=50, c='violet', zorder=3)
plt.plot([x,x1], [y,y1], color = 'w')
circle = plt.Circle((0, 0), 1, color='c', fill=False, lw = 1)
ax.add_artist(circle)
#Customize the axes and gridlines:
ax.grid(False)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['bottom'].set_visible(False)
#TickMarks Customization:
ax.set_xticks([])
ax.set_yticks([])
#plt.savefig('nthRoots.png', format='png', dpi=1000,bbox_inches='tight')
plt.show()
Output
Is it possible to animate n over different values?
EDIT: Here I donot have only scatter plots ...so I cannot understand how to do this job using those links..!
My Attempt
#Animation.
import matplotlib as mpl
mpl.rc('text', usetex = True) #for LaTex notation in the Plot
mpl.rc('font', family = 'serif')
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Circle
from matplotlib import animation, rc
rc('animation', html='html5')
fig = plt.subplots()
ax = plt.axes(xlim=(-1.2, 1.2), ylim=(-1.2, 1.2))
plt.gca().set_aspect('equal', adjustable='box')
plt.style.use(['ggplot','dark_background'])
plt.rcParams['figure.figsize'] = (12, 8)
p = 2
#Plotting Function:
def f(n):
for k in range(0,n,1):
theta1 = np.pi + 2*k*np.pi / n
theta2 = np.pi + 2*p*k*np.pi / n
x, y = np.cos(theta1), np.sin(theta1)
x1, y1 = np.cos(theta2), np.sin(theta2)
plt.scatter(x, y, s=50, c='violet', zorder=3)
plt.plot([x,x1], [y,y1], color = 'w')
circle = plt.Circle((0, 0), 1, color='c', fill=False, lw = 1)
ax.add_artist(circle)
#Customize the axes and gridlines:
ax.grid(False)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['bottom'].set_visible(False)
#TickMarks Customization:
ax.set_xticks([])
ax.set_yticks([])
plt.show()
#Now I try to define a function for animating n in f(n)
def animate(n):
f(n)
anim = animation.FuncAnimation(fig, animate,
frames=100, interval=100, blit=True)
#anim.save('Wave.mp4', writer = 'ffmpeg', fps = 2, dpi=500,extra_args=['-vcodec', 'libx264'])
That's all I had... But this idea didn't work...I think I have to properly define animate(n).
Any suggestion...! thanks.
Several problems in your code (most are unrelated to animations)
rcParams need to be defined before creating the figure
plt.subplots returns a tuple of figure and axes.
The animation must return a sequence of artist objects when blitting is used. You might turn it off though
plt.show() should be called once at the end of the script.
Correcting for those you get
import matplotlib as mpl
mpl.rc('font', family = 'serif')
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Circle
from matplotlib import animation, rc
plt.rcParams['figure.figsize'] = (12, 8)
plt.style.use(['ggplot','dark_background'])
fig, ax = plt.subplots()
p = 2
#Plotting Function:
def f(n):
ax.clear()
ax.set(xlim=(-1.2, 1.2), ylim=(-1.2, 1.2))
ax.set_aspect('equal', adjustable='box')
for k in range(0,n,1):
theta1 = np.pi + 2*k*np.pi / n
theta2 = np.pi + 2*p*k*np.pi / n
x, y = np.cos(theta1), np.sin(theta1)
x1, y1 = np.cos(theta2), np.sin(theta2)
plt.scatter(x, y, s=50, c='violet', zorder=3)
plt.plot([x,x1], [y,y1], color = 'w')
circle = Circle((0, 0), 1, color='c', fill=False, lw = 1)
ax.add_artist(circle)
#Customize the axes and gridlines:
ax.grid(False)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['bottom'].set_visible(False)
#TickMarks Customization:
ax.set_xticks([])
ax.set_yticks([])
anim = animation.FuncAnimation(fig, f, frames=100, interval=100, blit=False)
plt.show()

Set equal aspect in plot with colorbar

I need to generate a plot with equal aspect in both axis and a colorbar to the right. I've tried setting aspect='auto', aspect=1, and aspect='equal' with no good results. See below for examples and the MWE.
Using aspect='auto' the colorbars are of the correct height but the plots are distorted:
Using aspect=1 or aspect='equal' the plots are square (equal aspect in both axis) but the colorbars are distorted:
In both plots the colorbars are positioned too far to the right for some reason. How can I get a square plot with colorbars of matching heights?
MWE
import numpy as np
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
def col_plot(params):
gs, i, data = params
xarr, yarr, zarr = zip(*data)[0], zip(*data)[1], zip(*data)[2]
xmin, xmax = min(xarr), max(xarr)
ymin, ymax = min(yarr), max(yarr)
#plt.subplot(gs[i], aspect='auto')
plt.subplot(gs[i], aspect=1)
#plt.subplot(gs[i], aspect='equal')
plt.xlim(xmin, xmax)
plt.ylim(xmin, xmax)
plt.xlabel('$x axis$', fontsize=20)
plt.ylabel('$y axis$', fontsize=20)
# Scatter plot.
cm = plt.cm.get_cmap('RdYlBu_r')
SC = plt.scatter(xarr, yarr, marker='o', c=zarr, s=60, lw=0.25, cmap=cm,
zorder=3)
# Colorbar.
ax0 = plt.subplot(gs[i + 1])
cbar = plt.colorbar(SC, cax=ax0)
cbar.set_label('$col bar$', fontsize=21, labelpad=-2)
# Generate data.
data0 = np.random.uniform(0., 1., size=(50, 3))
data1 = np.random.uniform(0., 1., size=(50, 3))
# Create the top-level container
fig = plt.figure(figsize=(14, 25))
gs = gridspec.GridSpec(4, 4, width_ratios=[1, 0.05, 1, 0.05])
# Generate plots.
par_lst = [[gs, 0, data0], [gs, 2, data1]]
for pl_params in par_lst:
col_plot(pl_params)
# Output png file.
fig.tight_layout()
plt.savefig('colorbar_aspect.png', dpi=300)
You can use an AxesDivider to do that. I have modified your code a bit to make use of an AxesDivider.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
def col_plot(data):
xarr, yarr, zarr = zip(*data)[0], zip(*data)[1], zip(*data)[2]
xarr = [2*x for x in xarr]
xmin, xmax = min(xarr), max(xarr)
ymin, ymax = min(yarr), max(yarr)
fig = plt.figure()
ax0 = fig.add_subplot(111, aspect='equal')
plt.xlim(xmin, xmax)
plt.ylim(ymin, ymax)
plt.xlabel('$x axis$', fontsize=20)
plt.ylabel('$y axis$', fontsize=20)
# Scatter plot.
cm = plt.cm.get_cmap('RdYlBu_r')
SC = ax0.scatter(xarr, yarr, marker='o', c=zarr, s=60, lw=0.25, cmap=cm,
zorder=3)
the_divider = make_axes_locatable(ax0)
color_axis = the_divider.append_axes("right", size="5%", pad=0.1)
# Colorbar.
cbar = plt.colorbar(SC, cax=color_axis)
cbar.set_label('$col bar$', fontsize=21, labelpad=-2)
# Generate data.
data0 = np.random.uniform(0., 1., size=(20, 3))
col_plot(data0)
And here is the result (I changed your data so it spans a range of [0, 2] in the x-direction for demonstration purposes):
On Joseph Long's blog there is the following nice solution.
1) Define a colorbar function as:
from mpl_toolkits.axes_grid1 import make_axes_locatable
def colorbar(mappable):
ax = mappable.axes
fig = ax.figure
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
return fig.colorbar(mappable, cax=cax)
2) Call colorbar(thing) when you want to make a colorbar. In your case:
SC = ax0.scatter(xarr, yarr, marker='o', c=zarr, s=60, lw=0.25, cmap=cm,
zorder=3)
colorbar(SC)
3) And you get:

How to add space for xticklabels in python?

all, I'm using Matplotlib to plot a polarbar. But the ticks are overlapped.
Does anybody know how to avoid this? Thanks!
from pylab import *
import matplotlib.pyplot as plt
from cf.plot import BoundaryNorm,getBoundCmap
from matplotlib import colors
fig = figure(figsize=(8,8))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True)
N = 8
theta = np.arange(0.0, 2*np.pi, 2*np.pi/N)
radii = ones((1,N)).squeeze()
width = 2*np.pi/N
bars = ax.bar(theta, radii, width=width, bottom=0.6)
listBnd = [0,3,6,9,12,15,18,21,24]
mcolors = plt.cm.Spectral(linspace(0,1,N))
cmap = colors.ListedColormap(mcolors)
for r,bar in zip(arange(1,N+1), bars):
bar.set_facecolor(cmap(r-1))
xlabels = array([0,21,18,15,12,9,6,3])
ax.xaxis.labelpad=50
ax.set_xticks(theta)
ax.set_xticklabels(xlabels,rotation=270,fontsize='60')
ax.xaxis.set_label_coords(0.5,-0.5)
ax.set_yticklabels([])
grid([])
show()
First off, let's clean up your code a bit. You have a lot of things that don't make sense. (For example, why generate a list of colors from the colormap, then create another colormap, then get the colors you originally generated from the other colormap?)
In addition, you're setting a lot of parameters that probably don't do what you think they do. (For example, the labelpad for an axis controls the padding for the axis label (e.g. xlabel), not for the ticks.)
With that in mind, your code might look something like this:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(111, projection='polar')
N = 8
theta = np.arange(0.0, 2*np.pi, 2*np.pi/N)
radii = np.ones(N)
width = 2 * np.pi / N
bars = ax.bar(theta, radii, width=width, bottom=0.6)
colors = plt.cm.Spectral(np.linspace(0, 1, N))
for color, bar in zip(colors, bars):
bar.set_facecolor(color)
xlabels = np.array([0,21,18,15,12,9,6,3])
ax.set_xticks(theta)
ax.set_xticklabels(xlabels, rotation=270, fontsize=60)
ax.set_yticklabels([])
ax.grid(False)
plt.show()
Which generates a figure similar to the following:
Basically, you want to use the frac kwarg to ax.set_thetagrids to change the radial position of the theta tick labels. (This is a bit hidden, but it's the easiest way to do it.)
In addition, I'm using fig.tight_layout to resize things so that the tick labels don't wind up outside of the figure boundaries.
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(111, projection='polar')
N = 8
theta = np.arange(0.0, 2*np.pi, 2*np.pi/N)
radii = np.ones(N)
width = 2 * np.pi / N
bars = ax.bar(theta, radii, width=width, bottom=0.6)
colors = plt.cm.Spectral(np.linspace(0, 1, N))
for color, bar in zip(colors, bars):
bar.set_facecolor(color)
xlabels = np.array([0,21,18,15,12,9,6,3])
ax.set_thetagrids(np.degrees(theta), xlabels, frac=1.2,
rotation=270, fontsize=60)
ax.set_yticklabels([])
ax.grid(False)
fig.tight_layout()
plt.show()

Categories

Resources