[英]How to make axis tick labels visible on the other side of the plot in gridspec?
[英]Python plot side by side with axis labels
我还没有看到这样的设置并感谢这里的指导 -
我有多个条形图(一周中的每一天),我想将它们与标签并排显示(使用 label 函数)。 现在,只有第一个图表绘制了标签。
plt.figure(1)
ax1 = plt.subplot(221)
ax = df[df.day_of_week=='Fri'].groupby('date').agg('amount').mean().plot(ax=ax1,kind='bar',x='date',y='amount')
# code for labels
def add_value_labels(plot,spacing=7):
for rect in ax.patches:
# Get X and Y placement of label from rect.
y = rect.get_height()
x = rect.get_x() + rect.get_width() / 2
space = spacing
va = 'bottom'
# If value of bar is negative: Place label below bar
if y < 0:
# Invert space to place label below
space *= -1
# Vertically align label at top
va = 'top'
label = "{:.1f}".format(y)
# Create annotation
ax.annotate(
label,
(x, y),
xytext=(0, space),
textcoords="offset points",
ha='center',
va=va)
add_value_labels(ax)
bx1=plt.subplot(222)
bx = df[df.day_of_week=='Sat'].groupby('date').agg('amount').mean().plot(ax=bx1,kind='bar',x='date',y='amount')
add_value_labels(bx)
如何在 label 功能正常工作的情况下并排显示这两个图?
在您的方法add_value_labels
中, plot
作为参数给出。 但是,您在方法内使用ax
,因此它将始终适用于在 function 之外定义的ax object
object,这是您的第一个 plot(仅限)。 如果您将ax
替换为plot
它应该可以工作。 这是我的代码,其中包含一些基本示例数据。
import pandas as pd
df= pd.DataFrame([["1.1.20", "Fri", 15], ["2.1.20", "Sat", 20], ["3.1.20", "Fri", -2], ["4.1.20","Sat", 2]], columns=["date","day_of_week","amount"])
plt.figure(1)
ax1 = plt.subplot(221)
ax = df[df.day_of_week=='Fri'].groupby('date').agg('amount').mean().plot(ax=ax1,kind='bar',x='date',y='amount')
# code for labels
def add_value_labels(plot,spacing=7):
for rect in plot.patches:
# Get X and Y placement of label from rect.
y = rect.get_height()
x = rect.get_x() + rect.get_width() / 2
space = spacing
va = 'bottom'
# If value of bar is negative: Place label below bar
if y < 0:
# Invert space to place label below
space *= -1
# Vertically align label at top
va = 'top'
label = "{:.1f}".format(y)
# Create annotation
plot.annotate(
label,
(x, y),
xytext=(0, space),
textcoords="offset points",
ha='center',
va=va)
add_value_labels(ax)
bx1=plt.subplot(222)
bx = df[df.day_of_week=='Sat'].groupby('date').agg('amount').mean().plot(ax=bx1,kind='bar',x='date',y='amount')
add_value_labels(bx)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.