Reputation: 4546
I'm trying to create a polar projection using matplotlib.pyplot.subplots()
but I get the error projection is not defined
when I try to pass a dictionary to matplotlib.pyplot.subplots()
My code:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(nrows=1, ncols=2, subplot_kw={projection:'polar'})
However plt.subplot(1,1,1, projection='polar')
works as expected. The documentation for plt.subplots()
says that the dictionary in subplot_kw
will be passed to add.subplot()
which takes projection as a optional parameter so I'm not sure what my mistake is.
Upvotes: 3
Views: 11058
Reputation: 1
This is mainly to clarify which was the mistake in the original post and to complete the previous answer.
Following the plt.subplots()
documentation you cited, the argument subplot_kw
is expected to be dictionary. There are two equivalent ways of doing this.
option 1:
Use the function dict()
to create the dictionary to pass:
subplot_kw = dict(projection = 'polar')
oprtion 2:
Pass directly the dictionary in with the correct key-value structure
subplot_kw = {'projection' : 'polar'}
Notice that in the first option the word projection
does not need to be a string and you can use and equal =
sign. The function dict
will do the job of formating the dictionary from its arguments. You can verify this simply by doing:
>>>dict(projection = 'polar')
Output: {'projection' : 'polar'}
Upvotes: 0
Reputation: 13185
The docs that you linked don't actually show subplot_kw
being used in that way. What they show is calling dict()
:
fig, axes = plt.subplots(2, 2, subplot_kw=dict(polar=True))
If you print the output of subplot_kw=dict(polar=True)
, you get:
{'polar': True}
Notice that polar
has now become a string. subplot_kw={projection:'polar'})
does not define projection
as a string, it's just a variable name that Python now has to look up (and it won't find it in this case, but it may find something else in other cases).
Upvotes: 7