我正在使用以下代码绘制极坐标条形图:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
Row1, Row2, Row3 = ['A',180,2], ['A',270,6], ['A',360,3]
df_polar = pd.DataFrame([Row1, Row2, Row3])
df_polar.columns = ['Type', 'Angle', 'Count']
df_polar = df_polar.set_index('Angle')
deg = np.pi/180
Angle = np.array(df_polar.index.tolist())
theta = Angle = Angle * deg
count = radii = df_polar['Count']
width = 30*deg
colors = plt.cm.viridis(df_polar['Count'] / 4.)
ax = plt.subplot(111, projection='polar')
ax.bar(theta, count, width=width, bottom=0, color=colors, alpha=.6)
ax.set_thetagrids(range(0, 360, 30))
ax.set_theta_zero_location("N") # Set 0 degrees to the top of the plot
ax.set_theta_direction(-1)
ax.set_rlabel_position(15)
plt.show()
当前的限制是,对于列"Type"的其他值,绘图的数量不按比例缩放。我曾尝试使用FacetGrid来解决这个问题(但收效甚微(:
import numpy as np
import pandas as pd
import seaborn as sns
sns.set()
Row1, Row2, Row3 , Row4 = ['A',180,2], ['A',270,6], ['A',360,3] , ['B',360,3]
df_polar = pd.DataFrame([Row1, Row2, Row3, Row4])
df_polar.columns = ['Type', 'Angle', 'Count']
# Generate an example radial datast
df = df_polar
# Set up a grid of axes with a polar projection
ax = sns.FacetGrid(df, col="Type", hue="Type",
subplot_kws=dict(projection='polar'), height=4.5,
sharex=False, sharey=False, despine=False)
# Draw a scatterplot onto each axes in the grid
ax.map(sns.scatterplot, "Angle", "Count")
我正在努力解决的问题是:从散点变为条形图、set_thetagrids、set_the _ zero_location、set_ther _ direction、set_rabel_position。
任何帮助都将不胜感激。非常感谢。
我希望可以像在R中一样简单地缩放python中的facet数量。但在短时间内,它太复杂了。因此,我设法使用"for循环"使其工作。希望有更简单的解决方案。解决方案发布在下面:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
Row1, Row2, Row3, Row4, Row5 = ['A',180,2], ['A',270,6], ['A',360,3], ['B',360,5], ['C',135,6]
df_polar = pd.DataFrame([Row1, Row2, Row3, Row4, Row5])
df_polar.columns = ['Type', 'Angle', 'Count']
deg = np.pi/180
width = 30*deg
fig = plt.figure()
fig.set_size_inches((15, 9), forward=False)
i=0
x = np.array(df_polar['Type'])
Total_types = np.unique(x)
for Type in Total_types:
i+=1
df_plot = df_polar[df_polar['Type'] == Type].set_index('Angle')
Angle = np.array(df_plot.index.tolist())
theta = Angle = Angle * deg
count = radii = df_plot['Count']
colors = plt.cm.viridis(df_plot['Count'] / 4.)
ax = fig.add_subplot(1,len(Total_types),i, projection='polar')
ax.bar(theta, count, width=width, bottom=0, color=colors, alpha=.6)
ax.set_thetagrids(range(0, 360, 30))
ax.set_theta_zero_location("N")
ax.set_theta_direction(-1)
ax.set_rlabel_position(15)
ax.set_title(Type, fontsize=15)
plt.tight_layout()
plt.show()