How to clip polar plot in pylab/pyplot

2024/10/3 23:21:21

I have a polar plot where theta varies from 0 to pi/2, so the whole plot lies in the first quater, like this:

%pylab inline
X=linspace(0,pi/2)
polar(X,cos(6*X)**2)

full polar plot, a lot's of space wasted
(source: schurov.com)

Is it possible by means of pyplot or matplotlib to clip the polar plot so that only first quater is shown (and therefore no space is wasted)? I want a picture like this (but properly scaled):

cropped plot that I want
(source: schurov.com)

I'd like to do it by means of pyplot because I have several images like this and want to arrange them into a big figure (with subplot). Is it possible?

Answer

I recommend not using the polar plot but instead setting up axis artists. This allows you to set up a 'partial' polar plot.

This answer is based on an adjustment of the 3rd example from: axes_grid example code: demo_floating_axes.py

import numpy as np
import matplotlib.pyplot as pltfrom matplotlib.transforms import Affine2D
import mpl_toolkits.axisartist.floating_axes as floating_axes
import mpl_toolkits.axisartist.angle_helper as angle_helper
from matplotlib.projections import PolarAxes
from mpl_toolkits.axisartist.grid_finder import MaxNLocator# define how your plots look:def setup_axes(fig, rect, theta, radius):# PolarAxes.PolarTransform takes radian. However, we want our coordinate# system in degreetr = Affine2D().scale(np.pi/180., 1.) + PolarAxes.PolarTransform()# Find grid values appropriate for the coordinate (degree).# The argument is an approximate number of grids.grid_locator1 = angle_helper.LocatorD(2)# And also use an appropriate formatter:tick_formatter1 = angle_helper.FormatterDMS()# set up number of ticks for the r-axisgrid_locator2 = MaxNLocator(4)# the extremes are passed to the functiongrid_helper = floating_axes.GridHelperCurveLinear(tr,extremes=(theta[0], theta[1], radius[0], radius[1]),grid_locator1=grid_locator1,grid_locator2=grid_locator2,tick_formatter1=tick_formatter1,tick_formatter2=None,)ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper)fig.add_subplot(ax1)# adjust axis# the axis artist lets you call axis with# "bottom", "top", "left", "right"ax1.axis["left"].set_axis_direction("bottom")ax1.axis["right"].set_axis_direction("top")ax1.axis["bottom"].set_visible(False)ax1.axis["top"].set_axis_direction("bottom")ax1.axis["top"].toggle(ticklabels=True, label=True)ax1.axis["top"].major_ticklabels.set_axis_direction("top")ax1.axis["top"].label.set_axis_direction("top")ax1.axis["left"].label.set_text("R")ax1.axis["top"].label.set_text(ur"$\alpha$ [\u00b0]")# create a parasite axesaux_ax = ax1.get_aux_axes(tr)aux_ax.patch = ax1.patch # for aux_ax to have a clip path as in axax1.patch.zorder=0.9 # but this has a side effect that the patch is# drawn twice, and possibly over some other# artists. So, we decrease the zorder a bit to# prevent this.return ax1, aux_ax#
# call the plot setup to generate 3 subplots
#fig = plt.figure(1, figsize=(8, 4))
fig.subplots_adjust(wspace=0.3, left=0.05, right=0.95)ax1, aux_ax1 = setup_axes(fig, 131, theta=[0, 90], radius=[0, 1])
ax2, aux_ax2 = setup_axes(fig, 132, theta=[0, 90], radius=[0, 1])
ax3, aux_ax3 = setup_axes(fig, 133, theta=[0, 90], radius=[0, 1])#
# generate the data to plot
#
theta = np.linspace(0,90) # in degrees
radius = np.cos(6.*theta * pi/180.0)**2.0# 
# populate the three subplots with the data
#
aux_ax1.plot(theta, radius, 'r')
aux_ax2.plot(theta, radius, 'b')
aux_ax3.plot(theta, radius, 'g')plt.show()  

And you'll end up with this plot:

enter image description here

The axisartist reference and the demo on a curvelinear grid provide some additional insight into how to use angle_helper. Especially with regard to which parts expect radians and which degrees.

https://en.xdnf.cn/q/70674.html

Related Q&A

Cython and c++ class constructors

Can someone suggest a way to manipulate c++ objects with Cython, when the c++ instance of one class is expected to feed the constructor of another wrapped class as described below? Please look at th…

How to share state when using concurrent futures

I am aware using the traditional multiprocessing library I can declare a value and share the state between processes. https://docs.python.org/3/library/multiprocessing.html?highlight=multiprocessing#s…

Does IronPython implement python standard library?

I tried IronPython some time ago and it seemed that it implements only python language, and uses .NET for libraries. Is this still the case? Can one use python modules from IronPython?

finding the last occurrence of an item in a list python

I wish to find the last occurrence of an item x in sequence s, or to return None if there is none and the position of the first item is equal to 0This is what I currently have:def PositionLast (x,s):co…

pandas cut a series with nan values

I would like to apply the pandas cut function to a series that includes NaNs. The desired behavior is that it buckets the non-NaN elements and returns NaN for the NaN-elements.import pandas as pd numbe…

Using Selenium with PyCharm CE

Im trying to use Selenium with PyCharm CE. I have installed Selenium using pip install Selenium and Im able to use it via the terminal however when I try to use it with PyCharm I get an import error Im…

Reusing generator expressions

Generator expressions is an extremely useful tool, and has a huge advantage over list comprehensions, which is the fact that it does not allocate memory for a new array.The problem I am facing with gen…

ModuleNotFoundError: No module named librosa

Currently I am working on voice recognition where I wanted to use Librosa library. I install librosa with the command on ubuntu: conda install -c conda-forge librosaBut when I run the code I got the fo…

Python - Convert Very Large (6.4GB) XML files to JSON

Essentially, I have a 6.4GB XML file that Id like to convert to JSON then save it to disk. Im currently running OSX 10.8.4 with an i7 2700k and 16GBs of ram, and running Python 64bit (double checked). …

Python create tree from a JSON file

Lets say that we have the following JSON file. For the sake of the example its emulated by a string. The string is the input and a Tree object should be the output. Ill be using the graphical notation …