I am plotting from a CSV file that contains Cartesian coordinates and I want to change it to Polar coordinates, then plot using the Polar coordinates.
Here is the code
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns
df = pd.read_csv('test_for_plotting.csv',index_col = 0)
x_temp = df['x'].values
y_temp = df['y'].values
df['radius'] = np.sqrt( np.power(x_temp,2) + np.power(y_temp,2) )
df['theta'] = np.arctan2(y_temp,x_temp)
df['degrees'] = np.degrees(df['theta'].values)
df['radians'] = np.radians(df['degrees'].values)
ax = plt.axes(polar = True)
ax.set_aspect('equal')
ax.axis("off")
sns.set(rc={'axes.facecolor':'white', 'figure.facecolor':'white','figure.figsize':(10,10)})
# sns.scatterplot(data = df, x = 'x',y = 'y', s= 1,alpha = 0.1, color = 'black',ax = ax)
sns.scatterplot(data = df, x = 'radians',y = 'radius', s= 1,alpha = 0.1, color = 'black',ax = ax)
plt.tight_layout()
plt.show()
Here is the dataset
If you run this command using polar = False and use this line to plot sns.scatterplot(data = df, x = 'x',y = 'y', s= 1,alpha = 0.1, color = 'black',ax = ax) it will result in this picture
now after setting polar = True and run this line to plot sns.scatterplot(data = df, x = 'radians',y = 'radius', s= 1,alpha = 0.1, color = 'black',ax = ax) It is supposed to give you this
But it is not working as if you run the actual code the shape in the Polar format is the same as Cartesian which does not make sense and it does not match the picture I showed you for polar (If you are wondering where did I get the second picture from, I plotted it using R)
I would appreciate your help and insights and thanks in advance!
For a polar plot, the "x-axis" represents the angle in radians. So, you need to switch x and y, and convert the angles to radians (I also added ax=ax, as the axes was created explicitly):
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns
data = {'radius': [0, 0.5, 1, 1.5, 2, 2.5], 'degrees': [0, 25, 75, 155, 245, 335]}
df_temp = pd.DataFrame(data)
ax = plt.axes(polar=True)
sns.scatterplot(x=np.radians(df_temp['degrees']), y=df_temp['radius'].to_numpy(),
s=100, alpha=1, color='black', ax=ax)
for deg, y in zip(df_temp['degrees'], df_temp['radius']):
x = np.radians(deg)
ax.axvline(x, color='skyblue', ls=':')
ax.text(x, y, f' {deg}', color='crimson')
ax.set_rlabel_position(-15) # Move radial labels away from plotted dots
plt.tight_layout()
plt.show()
About your new question: if you have an xy plot, and you convert these xy values to polar coordinates, and then plot these on a polar plot, you'll get again the same plot.
After some more testing with the data, I decided to create the plot directly with matplotlib, as seaborn makes some changes that don't have exactly equal effects across seaborn and matplotlib versions.
What seems to be happening in R:
The angles (given by "x") are spread out to fill the range (0,2 pi). This either requires a rescaling of x, or change how the x-values are mapped to angles. One way to get this, is subtracting the minimum. And with that result divide by the new maximum and multiply by 2 pi.
The 0 of the angles it at the top, and the angles go clockwise.
The following code should create the plot with Python. You might want to experiment with alpha and with s in the scatter plot options. (Default the scatter dots get an outline, which often isn't desired when working with very small dots, and can be removed by lw=0.)
ax = plt.axes(polar=True)
ax.set_aspect('equal')
ax.axis('off')
x_temp = df['x'].to_numpy()
y_temp = df['y'].to_numpy()
x_temp -= x_temp.min()
x_temp = x_temp / x_temp.max() * 2 * np.pi
ax.scatter(x=x_temp, y=y_temp, s=0.05, alpha=1, color='black', lw=0)
ax.set_rlim(y_temp.min(), y_temp.max())
ax.set_theta_zero_location("N") # set zero at the north (top)
ax.set_theta_direction(-1) # go clockwise
plt.show()
At the left the resulting image, at the right using the y-values for coloring (ax.scatter(..., c=y_temp, s=0.05, alpha=1, cmap='plasma_r', lw=0)):
I have a data with coordinates X,Y similar to a Vertical Sine function, I want to fill the area between left edge and the curve generated using variable color with colormap on matplot, changes in color whith X value as the image (From Blue to Red). I've tried and get this result where start point and final point are conected by a line. I need to fill the left area.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch
#Data
y=np.arange(0,10,0.01)
x=np.sin(y)*y+2
#Set Array
xx=np.asarray(x)
yy=np.asarray(y)
path = Path(np.array([xx,yy]).transpose())
patch = PathPatch(path, facecolor='none')
plt.gca().add_patch(patch)
im = plt.imshow(xx.reshape(yy.size,1), cmap=plt.cm.coolwarm,interpolation="nearest",
origin='left',extent=[-5,10,0,10],aspect="auto", clip_path=patch, clip_on=True)
im.set_clip_path(patch)
You could add two additional points lying on the y-axis to create the desired shape:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch
y = np.linspace(0, 10, 200)
x = np.sin(y) * y + 2
path = Path(np.array([np.append(x, [-5, -5]), np.append(y, [y[-1], y[0]])]).T)
patch = PathPatch(path, facecolor='none')
plt.gca().add_patch(patch)
im = plt.imshow(x.reshape(y.size, 1), cmap=plt.cm.coolwarm, interpolation="nearest",
origin='lower', extent=[-5, 10, 0, 10], aspect="auto", clip_path=patch, clip_on=True)
plt.show()
I'm trying to adapt the Cartopy example plot for circular South Polar Stereographic plots to the North Pole and add data to it. I have a couple questions.
First, in the example code, the land feature is added before the ocean feature. When I did that, I got a map with only ocean. I reversed the order of the call in the code below and get a map with land and ocean. Why did the other order work with the South Polar example?
Second, and more importantly, I can't figure out why my pcolormesh call isn't having any effect.
I'm using Python 2.7.7, matplotlib 1.5.1, and Cartopy 0.15.1.
import matplotlib.path as mpath
import matplotlib.pyplot as plt
import numpy as np
import cartopy.crs as ccrs
import cartopy.feature
lats = np.linspace(60,90,30)
lons = np.linspace(0,360,200)
X,Y = np.meshgrid(lons,lats)
Z = np.random.normal(size = X.shape)
def main():
fig = plt.figure(figsize=[10, 5])
ax = plt.subplot(1, 1, 1, projection=ccrs.NorthPolarStereo())
fig.subplots_adjust(bottom=0.05, top=0.95,
left=0.04, right=0.95, wspace=0.02)
# Limit the map to -60 degrees latitude and below.
ax.set_extent([-180, 180, 60, 60], ccrs.PlateCarree())
ax.gridlines()
ax.add_feature(cartopy.feature.OCEAN)
ax.add_feature(cartopy.feature.LAND)
# Compute a circle in axes coordinates, which we can use as a boundary
# for the map. We can pan/zoom as much as we like - the boundary will be
# permanently circular.
theta = np.linspace(0, 2*np.pi, 100)
center, radius = [0.5, 0.5], 0.5
verts = np.vstack([np.sin(theta), np.cos(theta)]).T
circle = mpath.Path(verts * radius + center)
ax.set_boundary(circle, transform=ax.transAxes)
ax.pcolormesh(X,Y,Z,transform=ccrs.PlateCarree())
plt.show()
if __name__ == '__main__':
main()
Your code leaves cartopy to dictate the order of feature plots on the map, as a result, some features can be hidden with no clues. It is possible to specify the order of plots explicitly.
The order of features plot is controlled by zorder, which can be specified with zorder=integer in most plotting statements. Here is a modified code that produces a better plot.
# your data
lats = np.linspace(60, 90, 30)
lons = np.linspace(0, 360, 160)
X,Y = np.meshgrid(lons, lats)
Z = np.random.normal(size = X.shape)
# new data for pcolormesh plot
latz = np.linspace(75, 90, 15)
lonz = np.linspace(0, 360, 160)
X1,Y1 = np.meshgrid(lonz, latz)
Z1 = np.random.normal(size = X1.shape)
def main():
fig = plt.figure(figsize=[10, 10])
ax = plt.subplot(1, 1, 1, projection=ccrs.NorthPolarStereo())
fig.subplots_adjust(bottom=0.05, top=0.95,
left=0.04, right=0.95, wspace=0.02)
# Limit the map to -60 degrees latitude and below.
ax.set_extent([-180, 180, 60, 60], ccrs.PlateCarree())
ax.gridlines()
# zorder can be used to arrange what is on top
ax.add_feature(cartopy.feature.LAND, zorder=4) # land is specified to plot above ...
ax.add_feature(cartopy.feature.OCEAN, zorder=1) # ... the ocean
# Compute a circle in axes coordinates, which we can use as a boundary
# for the map. We can pan/zoom as much as we like - the boundary will be
# permanently circular.
theta = np.linspace(0, 2*np.pi, 100)
center, radius = [0.5, 0.5], 0.5
verts = np.vstack([np.sin(theta), np.cos(theta)]).T
circle = mpath.Path(verts * radius + center)
ax.set_boundary(circle, transform=ax.transAxes)
# pcolormesh is specified to plot on top of the ocean but below land
ax.pcolormesh(X1, Y1, Z1, transform=ccrs.PlateCarree(), zorder=3)
plt.show()
if __name__ == '__main__':
main()
I'm trying to generate an equatorial coordinates plot that should look more or less like this one:
(The figure is taken from this article, and it shows the position of the Large and Small MCs in equatorial coordinates)
Important things to notice about this plot:
The theta axis (ie: the right ascension) is in h:m:s (hours, minutes, seconds) as it is accustomed in astronomy, rather than in degrees as the default polar option does in matplotlib.
The r axis (ie: the declination) increases outward from -90º and the grid is centered in (0h, -90º).
The plot is clipped, meaning only a portion of it shows as opposed to the entire circle (as matplotlib does by default).
Using the polar=True option in matplotlib, the closest plot I've managed to produce is this (MWE below, data file here; some points are not present compared to the image above since the data file is a bit smaller):
I also need to add a third column of data to the plot, which is why I add a colorbar and color each point accordingly to a z array:
So what I mostly need right now is a way to clip the plot. Based mostly on this question and this example #cphlewis came quite close with his answer, but several things are still missing (mentioned in his answer).
Any help and/or pointers with this issue will be greatly appreciated.
MWE
(Notice I use gridspec to position the subplot because I need to generate several of these in the same output image file)
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
def skip_comments(f):
'''
Read lines that DO NOT start with a # symbol.
'''
for line in f:
if not line.strip().startswith('#'):
yield line
def get_data_bb():
'''RA, DEC data file.
'''
# Path to data file.
out_file = 'bb_cat.dat'
# Read data file
with open(out_file) as f:
ra, dec = [], []
for line in skip_comments(f):
ra.append(float(line.split()[0]))
dec.append(float(line.split()[1]))
return ra, dec
# Read RA, DEC data from file.
ra, dec = get_data_bb()
# Convert RA from decimal degrees to radians.
ra = [x / 180.0 * 3.141593 for x in ra]
# Make plot.
fig = plt.figure(figsize=(20, 20))
gs = gridspec.GridSpec(4, 2)
# Position plot in figure using gridspec.
ax = plt.subplot(gs[0], polar=True)
ax.set_ylim(-90, -55)
# Set x,y ticks
angs = np.array([330., 345., 0., 15., 30., 45., 60., 75., 90., 105., 120.])
plt.xticks(angs * np.pi / 180., fontsize=8)
plt.yticks(np.arange(-80, -59, 10), fontsize=8)
ax.set_rlabel_position(120)
ax.set_xticklabels(['$22^h$', '$23^h$', '$0^h$', '$1^h$', '$2^h$', '$3^h$',
'$4^h$', '$5^h$', '$6^h$', '$7^h$', '$8^h$'], fontsize=10)
ax.set_yticklabels(['$-80^{\circ}$', '$-70^{\circ}$', '$-60^{\circ}$'],
fontsize=10)
# Plot points.
ax.scatter(ra, dec, marker='o', c='k', s=1, lw=0.)
# Use this block to generate colored points with a colorbar.
#cm = plt.cm.get_cmap('RdYlBu_r')
#z = np.random.random((len(ra), 1)) # RGB values
#SC = ax.scatter(ra, dec, marker='o', c=z, s=10, lw=0., cmap=cm)
# Colorbar
#cbar = plt.colorbar(SC, shrink=1., pad=0.05)
#cbar.ax.tick_params(labelsize=8)
#cbar.set_label('colorbar', fontsize=8)
# Output png file.
fig.tight_layout()
plt.savefig(ra_dec_plot.png', dpi=300)
Getting the colorbar can be done with a merging of the OP code with #cphlewis's excellent answer. I've posted this as a turnkey solution on the request of the OP in chat. The first version of code simply adds a color bar, the final version (under EDIT 2) does an axes affine translation and corrects a few parameters / simplifies the code to suit OP spec exactly.
"""
An experimental support for curvilinear grid.
"""
import numpy as np
import mpl_toolkits.axisartist.angle_helper as angle_helper
import matplotlib.cm as cmap
from matplotlib.projections import PolarAxes
from matplotlib.transforms import Affine2D
from mpl_toolkits.axisartist import SubplotHost
from mpl_toolkits.axisartist import GridHelperCurveLinear
def curvelinear_test2(fig):
"""
polar projection, but in a rectangular box.
"""
global ax1
# see demo_curvelinear_grid.py for details
tr = Affine2D().scale(np.pi/180., 1.) + PolarAxes.PolarTransform()
extreme_finder = angle_helper.ExtremeFinderCycle(10, 60,
lon_cycle = 360,
lat_cycle = None,
lon_minmax = None,
lat_minmax = (0, np.inf),
)
grid_locator1 = angle_helper.LocatorHMS(12) #changes theta gridline count
tick_formatter1 = angle_helper.FormatterHMS()
grid_locator2 = angle_helper.LocatorDMS(6)
tick_formatter2 = angle_helper.FormatterDMS()
grid_helper = GridHelperCurveLinear(tr,
extreme_finder=extreme_finder,
grid_locator1=grid_locator1,
tick_formatter1=tick_formatter1,
grid_locator2=grid_locator2,
tick_formatter2=tick_formatter2
)
ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)
# make ticklabels of right and top axis visible.
ax1.axis["right"].major_ticklabels.set_visible(True)
ax1.axis["top"].major_ticklabels.set_visible(True)
ax1.axis["bottom"].major_ticklabels.set_visible(True) #Turn off?
# let right and bottom axis show ticklabels for 1st coordinate (angle)
ax1.axis["right"].get_helper().nth_coord_ticks=0
ax1.axis["bottom"].get_helper().nth_coord_ticks=0
fig.add_subplot(ax1)
grid_helper = ax1.get_grid_helper()
ax1.set_aspect(1.)
ax1.set_xlim(-4,15) # moves the origin left-right in ax1
ax1.set_ylim(-3, 20) # moves the origin up-down
ax1.set_ylabel('90$^\circ$ + Declination')
ax1.set_xlabel('Ascension')
ax1.grid(True)
#ax1.grid(linestyle='--', which='x') # either keyword applies to both
#ax1.grid(linestyle=':', which='y') # sets of gridlines
return tr
import matplotlib.pyplot as plt
fig = plt.figure(1, figsize=(5, 5))
fig.clf()
tr = curvelinear_test2(fig) # tr.transform_point((x, 0)) is always (0,0)
# => (theta, r) in but (r, theta) out...
r_test = [0, 1.2, 2.8, 3.8, 5, 8, 10, 13.3, 17] # distance from origin
deg_test = [0, -7, 12, 28, 45, 70, 79, 90, 100] # degrees ascension
out_test = tr.transform(zip(deg_test, r_test))
sizes = [40, 30, 10, 30, 80, 33, 12, 48, 45]
#hues = [.9, .3, .2, .8, .6, .1, .4, .5,.7] # Oddly, floats-to-colormap worked for a while.
hues = np.random.random((9,3)) #RGB values
# Use this block to generate colored points with a colorbar.
cm = plt.cm.get_cmap('RdYlBu_r')
z = np.random.random((len(r_test), 1)) # RGB values
SC = ax1.scatter(out_test[:,0], #ax1 is a global
out_test[:,1],
s=sizes,
c=z,
cmap=cm,
zorder=9) #on top of gridlines
# Colorbar
cbar = plt.colorbar(SC, shrink=1., pad=0.05)
cbar.ax.tick_params(labelsize=8)
cbar.set_label('colorbar', fontsize=8)
plt.show()
EDIT
Bit of tidying parameters, adding in OP data, removing redundancy yields the following plot. Still need to centre the data on -90 instead of 0 - at the moment this is hacked, but I'm sure curvelinear_test2() can be changed to account for it...
EDIT 2
Following OP comment on intermediate version in this answer, a final version as below gives the plot at the very end of the post - with -90 on the dec axis and subplot demo
"""
An experimental support for curvilinear grid.
"""
import numpy as np
import mpl_toolkits.axisartist.angle_helper as angle_helper
import matplotlib.cm as cmap
from matplotlib.projections import PolarAxes
from matplotlib.transforms import Affine2D
from mpl_toolkits.axisartist import SubplotHost
from mpl_toolkits.axisartist import GridHelperCurveLinear
def curvelinear_test2(fig, rect=111):
"""
polar projection, but in a rectangular box.
"""
# see demo_curvelinear_grid.py for details
tr = Affine2D().translate(0,90) + Affine2D().scale(np.pi/180., 1.) + PolarAxes.PolarTransform()
extreme_finder = angle_helper.ExtremeFinderCycle(10, 60,
lon_cycle = 360,
lat_cycle = None,
lon_minmax = None,
lat_minmax = (-90, np.inf),
)
grid_locator1 = angle_helper.LocatorHMS(12) #changes theta gridline count
tick_formatter1 = angle_helper.FormatterHMS()
grid_helper = GridHelperCurveLinear(tr,
extreme_finder=extreme_finder,
grid_locator1=grid_locator1,
tick_formatter1=tick_formatter1
)
ax1 = SubplotHost(fig, rect, grid_helper=grid_helper)
# make ticklabels of right and top axis visible.
ax1.axis["right"].major_ticklabels.set_visible(True)
ax1.axis["top"].major_ticklabels.set_visible(True)
ax1.axis["bottom"].major_ticklabels.set_visible(True) #Turn off?
# let right and bottom axis show ticklabels for 1st coordinate (angle)
ax1.axis["right"].get_helper().nth_coord_ticks=0
ax1.axis["bottom"].get_helper().nth_coord_ticks=0
fig.add_subplot(ax1)
grid_helper = ax1.get_grid_helper()
# You may or may not need these - they set the view window explicitly rather than using the
# default as determined by matplotlib with extreme finder.
ax1.set_aspect(1.)
ax1.set_xlim(-4,25) # moves the origin left-right in ax1
ax1.set_ylim(-3, 30) # moves the origin up-down
ax1.set_ylabel('Declination')
ax1.set_xlabel('Ascension')
ax1.grid(True)
#ax1.grid(linestyle='--', which='x') # either keyword applies to both
#ax1.grid(linestyle=':', which='y') # sets of gridlines
return ax1,tr
def skip_comments(f):
'''
Read lines that DO NOT start with a # symbol.
'''
for line in f:
if not line.strip().startswith('#'):
yield line
def get_data_bb():
'''RA, DEC data file.
'''
# Path to data file.
out_file = 'bb_cat.dat'
# Read data file
with open(out_file) as f:
ra, dec = [], []
for line in skip_comments(f):
ra.append(float(line.split()[0]))
dec.append(float(line.split()[1]))
return ra, dec
import matplotlib.pyplot as plt
fig = plt.figure(1, figsize=(5, 5))
fig.clf()
ax1, tr = curvelinear_test2(fig,121) # tr.transform_point((x, 0)) is always (0,0)
# => (theta, r) in but (r, theta) out...
# Read RA, DEC data from file.
ra, dec = get_data_bb()
out_test = tr.transform(zip(ra, dec))
# Use this block to generate colored points with a colorbar.
cm = plt.cm.get_cmap('RdYlBu_r')
z = np.random.random((len(ra), 1)) # RGB values
SC = ax1.scatter(out_test[:,0], #ax1 is a global
out_test[:,1],
marker = 'o',
c=z,
cmap=cm,
lw = 0.,
zorder=9) #on top of gridlines
# Colorbar
cbar = plt.colorbar(SC, shrink=1., pad=0.1)
cbar.ax.tick_params(labelsize=8)
cbar.set_label('colorbar', fontsize=8)
ax2, tr = curvelinear_test2(fig,122) # tr.transform_point((x, 0)) is always (0,0)
# => (theta, r) in but (r, theta) out...
# Read RA, DEC data from file.
ra, dec = get_data_bb()
out_test = tr.transform(zip(ra, dec))
# Use this block to generate colored points with a colorbar.
cm = plt.cm.get_cmap('RdYlBu_r')
z = np.random.random((len(ra), 1)) # RGB values
SC = ax2.scatter(out_test[:,0], #ax1 is a global
out_test[:,1],
marker = 'o',
c=z,
cmap=cm,
lw = 0.,
zorder=9) #on top of gridlines
# Colorbar
cbar = plt.colorbar(SC, shrink=1., pad=0.1)
cbar.ax.tick_params(labelsize=8)
cbar.set_label('colorbar', fontsize=8)
plt.show()
Final plot:
Chewing on the AxisArtist example is actually pretty promising (this combines two AxisArtist examples -- I wouldn't be surprised if AxisArtist was written with RA plots in mind):
Still to do:
Declination should run from -90 at the origin to 0
Be able to use
and add a colorbar
adjust limits if plotting outside them
aesthetic:
Serif font in axis labels
Dashed gridlines for ascension
anything else?
"""
An experimental support for curvilinear grid.
"""
import numpy as np
import mpl_toolkits.axisartist.angle_helper as angle_helper
import matplotlib.cm as cmap
from matplotlib.projections import PolarAxes
from matplotlib.transforms import Affine2D
from mpl_toolkits.axisartist import SubplotHost
from mpl_toolkits.axisartist import GridHelperCurveLinear
def curvelinear_test2(fig):
"""
polar projection, but in a rectangular box.
"""
global ax1
# see demo_curvelinear_grid.py for details
tr = Affine2D().scale(np.pi/180., 1.) + PolarAxes.PolarTransform()
extreme_finder = angle_helper.ExtremeFinderCycle(10, 60,
lon_cycle = 360,
lat_cycle = None,
lon_minmax = None,
lat_minmax = (0, np.inf),
)
grid_locator1 = angle_helper.LocatorHMS(12) #changes theta gridline count
tick_formatter1 = angle_helper.FormatterHMS()
grid_locator2 = angle_helper.LocatorDMS(6)
tick_formatter2 = angle_helper.FormatterDMS()
grid_helper = GridHelperCurveLinear(tr,
extreme_finder=extreme_finder,
grid_locator1=grid_locator1,
tick_formatter1=tick_formatter1,
grid_locator2=grid_locator2,
tick_formatter2=tick_formatter2
)
ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper)
# make ticklabels of right and top axis visible.
ax1.axis["right"].major_ticklabels.set_visible(True)
ax1.axis["top"].major_ticklabels.set_visible(True)
ax1.axis["bottom"].major_ticklabels.set_visible(True) #Turn off?
# let right and bottom axis show ticklabels for 1st coordinate (angle)
ax1.axis["right"].get_helper().nth_coord_ticks=0
ax1.axis["bottom"].get_helper().nth_coord_ticks=0
fig.add_subplot(ax1)
grid_helper = ax1.get_grid_helper()
ax1.set_aspect(1.)
ax1.set_xlim(-4,15) # moves the origin left-right in ax1
ax1.set_ylim(-3, 20) # moves the origin up-down
ax1.set_ylabel('90$^\circ$ + Declination')
ax1.set_xlabel('Ascension')
ax1.grid(True)
#ax1.grid(linestyle='--', which='x') # either keyword applies to both
#ax1.grid(linestyle=':', which='y') # sets of gridlines
return tr
import matplotlib.pyplot as plt
fig = plt.figure(1, figsize=(5, 5))
fig.clf()
tr = curvelinear_test2(fig) # tr.transform_point((x, 0)) is always (0,0)
# => (theta, r) in but (r, theta) out...
r_test = [0, 1.2, 2.8, 3.8, 5, 8, 10, 13.3, 17] # distance from origin
deg_test = [0, -7, 12, 28, 45, 70, 79, 90, 100] # degrees ascension
out_test = tr.transform(zip(deg_test, r_test))
sizes = [40, 30, 10, 30, 80, 33, 12, 48, 45]
#hues = [.9, .3, .2, .8, .6, .1, .4, .5,.7] # Oddly, floats-to-colormap worked for a while.
hues = np.random.random((9,3)) #RGB values
ax1.scatter(out_test[:,0], #ax1 is a global
out_test[:,1],
s=sizes,
c=hues,
#cmap=cmap.RdYlBu_r,
zorder=9) #on top of gridlines
plt.show()
I think it may be a problem with Python 3+ , now the line
out_test = tr.transform(zip(deg_test, r_test))
returns the error:
ValueError: cannot reshape array of size 1 into shape (2)
Changing the line to
out_test = tr.transform(list(zip(deg_test, r_test)))
fixes the problem and allows the plot to be generated correctly.