Skip to content

Instantly share code, notes, and snippets.

@dyerrington
Created November 7, 2019 19:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dyerrington/4f729e526b7001217b36ba75fa180e42 to your computer and use it in GitHub Desktop.
Save dyerrington/4f729e526b7001217b36ba75fa180e42 to your computer and use it in GitHub Desktop.
Basic implementation of a matplotlib polar plot using a basic observations with multiple variables.
from math import pi
from mpl_toolkits.axes_grid.inset_locator import inset_axes
# Set data
df = pd.DataFrame({
# 'group': ['A','B','C','D'],
'var1': [38, 1.5, 30, 4],
'var2': [29, 10, 9, 34],
'var3': [8, 39, 23, 24],
'var4': [7, 31, 33, 14]
})
def plot_polar(df, column = "var1", row = 0, figsize = (8, 8), title = False, ax = False):
# number of variable
categories = df.columns.tolist()
N = df.columns.size
# We are going to plot the first line of the data frame.
# But we need to repeat the first value to close the circular graph:
values = df.loc[row].tolist() + [df.iloc[row, 0].tolist()]
# What will be the angle of each axis in the plot? (we divide the plot / number of variable)
angles = [n / float(N) * 2 * pi for n in range(N)]
angles += angles[:1]
# Initialise the spider plot
if not ax:
ax = plt.subplot(111, polar = True)
if title:
plt.title(title, size = 14, pad = 50)
# Draw one axe per variable + add labels labels yet
plt.xticks(
angles[:-1],
categories,
color = 'grey',
size = 12
)
# Draw ylabels
ax.set_rlabel_position(0)
plt.yticks(
[.2,.4,.6,.8],
[".2",".4",".6",".8"],
# color = "grey",
size = 12,
)
plt.ylim(0,1)
# Plot data
ax.plot(
angles,
values,
linewidth = 1,
linestyle = 'solid'
);
# Fill area
ax.fill(angles, values, 'b', alpha=0.1)
plt.close()
return ax
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment