我试着用matplotlib注释水平条形图中的前倾。问题是,当我试图添加precentage注释时,会出现错误:
“模块'matplotlib.pyplot‘没有属性’修补程序‘
这就是我试图创建图表的方式:
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
%matplotlib inline
sns.set(style="whitegrid")
#sns.set_color_codes("Spectral")
plt.figure(2, figsize=(20,15))
the_grid = GridSpec(2, 2)
plt.subplot(the_grid[0, 1], title='Original Dataset')
sns.barplot(x='count',y='land_cover_specific', data=df, palette='Spectral')
plt.xlabel('Count')
plt.ylabel('Land cover')
total = len(original)
print(total)
for p in plt.patches:
percentage = '{:.1f}%'.format(100 * p.get_width()/total)
x = p.get_x() + p.get_width() + 0.02
y = p.get_y() + p.get_height()/2
plt.annotate(percentage, (x, y))
plt.show()
我得到了条形图,但是由于这个错误,我没有得到注释。
我的最终目标是:从总数中增加每一个条子的数目。
发布于 2020-10-21 22:50:46
我认为你只需要改变:
sns.barplot(x='count',y='land_cover_specific', data=df, palette='Spectral')
至:
ax = sns.barplot(x='count',y='land_cover_specific', data=df, palette='Spectral')
和
for p in plt.patches:
至:
for p in ax.patches:
发布于 2020-10-21 22:48:06
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
%matplotlib inline
sns.set(style="whitegrid")
#sns.set_color_codes("Spectral")
plt.figure(2, figsize=(20,15))
the_grid = GridSpec(2, 2)
plt.subplot(the_grid[0, 1], title='Original Dataset')
horizontal = sns.barplot(x='count',y='land_cover_specific', data=df, palette='Spectral')
plt.xlabel('Count')
plt.ylabel('Land cover')
total = len(original)
# print(total)
# for p in plt.patches:
# percentage = '{:.1f}%'.format(100 * p.get_width()/total)
# x = p.get_x() + p.get_width() + 0.02
# y = p.get_y() + p.get_height()/2
# plt.annotate(percentage, (x, y))
def auto_label(horizontal_):
for index, rectangle in enumerate(horizontal_):
height = rectangle.get_height()
width = rectangle.get_width()
y_value = rectangle.get_y()
# color is an array containing either hex or rgb values
# each should map to the color of each in your barchart
plt.text(width + height/2., y_value, "%d" % 100 * width / total, color=color[index])
auto_label(horizontal)
plt.show()
https://stackoverflow.com/questions/64476553
复制