Python组合图在条形图上添加百分比,但错误

Python组合图在条形图上添加百分比,但错误,python,pandas,matplotlib,visualization,seaborn,Python,Pandas,Matplotlib,Visualization,Seaborn,我尝试在组合图、折线图和柱形图中的条形图上添加百分比。 但是,显示的所有值都很混乱 我在这里提供数据,这也是我的,答案由提供 我提供了我尝试过的代码: fig, ax1 = plt.subplots(figsize=(7,5)) ax2=ax1.twinx() sns.lineplot(x='yq',y='Value2', data=dataset, hue='Group', ax=ax1, legend = None) ax1.set_xticklabels(ax1.get_xticks(),

我尝试在组合图、折线图和柱形图中的条形图上添加百分比。
但是,显示的所有值都很混乱

我在这里提供数据,这也是我的,答案由提供

我提供了我尝试过的代码:

fig, ax1 = plt.subplots(figsize=(7,5))
ax2=ax1.twinx()
sns.lineplot(x='yq',y='Value2', data=dataset, hue='Group', ax=ax1, legend = None)
ax1.set_xticklabels(ax1.get_xticks(), rotation=45)
ax1.set_ylabel("")
ax1.set_ylim((min(dataset['Value2']) - 0.05, max(dataset['Value2']) + 0.05))
sns.barplot(x='yq', y='Value1', data=dataset, hue='Group',ax=ax2)
ax2.set_yticklabels(['{:.1f}%'.format(a*100) for a in ax2.get_yticks()])
ax2.set_ylabel("")
for index, row in dataset.iterrows():
    ax2.text(row.name,row['Value1'], '{:.1f}%'.format(round(row['Value1'],2)), color='black')
plt.show()
绘图上显示的百分比杂乱无章,无法正确放置在每个栏和组上。
我继续搜索,但无法解决它。
有解决办法吗

我提供我的结果:

我还提供了由
R
的包
ggplot2
创建的正确结果图像
Python
中有两个类似于
ggplot2
的包,
plotnine
ggplot
。但是,我不能在Python中使用它。

如果有帮助,我将提供我的R代码作为您的参考:

library(data.table)
library(ggplot2)
library(zoo)
dataset <- fread("Group   yq        Value1    Value2
G       2014/1/1     0.07        1.1
G       2014/4/1     0.06        1.09
G       2014/7/1     0.09        1.11
G       2014/10/1     0.04        1.13
I       2014/1/1     0.10        1.2
I       2014/4/1     0.13        1.25
I       2014/7/1     0.15        1.23
I       2014/10/1     0.18        1.4", header = T)
dataset$yq <- as.Date(dataset$yq)
dataset[, yq := as.yearqtr(dataset$yq, format = "%Y-%m-%d")]

ggplot(data = dataset, aes(x = yq, colour = Group, fill = Group,
                           label = scales::percent(Value1, accuracy = 0.1))) + 
  geom_col(aes(y = sec_axis_mult * Value1), position = position_dodge2(width = 0)) +
  geom_line(aes(y = Value2)) +
  scale_colour_manual(values = c("red", "darkblue"), labels = c("G", "I")) +
  scale_fill_manual(values = c("red", "darkblue"), labels = NULL, breaks = NULL) +
  scale_x_yearqtr(format = "%YQ%q", breaks = unique(dataset$yq)) +
  scale_y_continuous(name = "Value2",
                     sec.axis = sec_axis(~./sec_axis_mult, name = "Value1",
                                         labels = scales::percent)) +
  theme_bw() +
  theme(axis.title.x = element_blank(),
        axis.title.y = element_blank(),
        axis.title.y.right = element_blank(),
        axis.ticks.x=element_blank(),
        axis.ticks.y=element_blank(),
        axis.text.x=element_text(angle = 45, size = 12, vjust = 0.5, face = "bold"),
        axis.text.y=element_blank(),
        axis.line = element_line(colour = "white"),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border = element_blank(),
        panel.background = element_blank(),
        plot.background=element_blank(),
        legend.position="left",
        legend.title=element_blank(),
        legend.text = element_text(size = 16, face = "bold"),
        legend.key = element_blank(),
        legend.box.background =  element_blank()) +
  guides(colour = guide_legend(override.aes = list(shape = 15, size = 10))) +
  geom_text(data = dataset, aes(y = sec_axis_mult * Value1, colour = Group), 
            position = position_dodge(width = 0.25),
            vjust = -0.3, size = 4)
库(data.table)
图书馆(GG2)
图书馆(动物园)

dataset我所做的是根据条形函数绘制的每个面片的坐标动态标记条形图

fig, ax1 = plt.subplots(figsize=(7,5))
ax2=ax1.twinx()
sns.lineplot(x='yq',y='Value2', data=dataset, hue='Group', ax=ax1, legend = None)
ax1.set_xticklabels(ax1.get_xticks(), rotation=45)
ax1.set_ylabel("")
ax1.set_ylim((min(dataset['Value2']) - 0.05, max(dataset['Value2']) + 0.05))
sns.barplot(x='yq', y='Value1', data=dataset, hue='Group',ax=ax2)
ax2.set_yticklabels(['{:.1f}%'.format(a*100) for a in ax2.get_yticks()])
ax2.set_ylabel("")
#iterate through each group of bars
for group in ax2.containers:
    for bar in group:
        #label the bar graphs based on the coordinates of the bar patches
        ax2.text(
            bar.get_xy()[0]+bar.get_width()/2,
            bar.get_height(), 
            '{:.1f}%'.format(round(100*bar.get_height(),2)), 
            color='black',
            horizontalalignment='center'
        )
输出:

我已经对代码进行了调整,使其与添加到原始问题中的所需输出更加匹配

fig, ax1 = plt.subplots(figsize=(7,5))
ax2=ax1.twiny().twinx()
sns.lineplot(x='yq',y='Value2', data=dataset, hue='Group', ax=ax1, legend = None)
ax1.set_xticklabels(dataset['yq'], rotation=45)
ax1.set_ylabel("")
ax1.set_ylim((0, max(dataset['Value2']) + 0.05))
ax2.set_ylim(0, max(dataset['Value2']) + 0.05)
sns.barplot(x='yq', y='Value1', data=dataset, hue='Group',ax=ax2)

#iterate through each group of bars
for group in ax2.containers:
    for bar in group:
        #label the bar graphs based on the coordinates of the bar patches
        ax2.text(
            bar.get_xy()[0]+bar.get_width()/2,
            bar.get_height(), 
            '{:.1f}%'.format(100*bar.get_height()), 
            color='black',
            horizontalalignment='center'
        )

ax1.yaxis.set_visible(False)
ax2.yaxis.set_visible(False)
ax2.xaxis.set_visible(False)
产出:

你能嵌入生成的绘图的图像吗?我在上面添加了图像,还提供了所需的绘图。就我个人而言,我会用它来渲染百分比,但我的代码与问题如何标记百分比保持一致。你能提供你将使用的
PercentFormatter
代码吗?PercentFormatter不会在轴上绘制。可以在轴上设置记号的格式。在原始代码中,您用百分比标记了所有标记,但您可以将轴标记器设置为PercentFormatter,然后将十进制值标记为百分比。
group
是一个条形容器对象数组。每个条都应该有一个facecolor属性,但我不建议将文本设置为与条相同的颜色,因为这样会使文本难以阅读。如果您想要红色和蓝色作为颜色,请尝试
color=bar.get\u facecolor()
。您可以更改seaborn调色板。
fig, ax1 = plt.subplots(figsize=(7,5))
ax2=ax1.twiny().twinx()
sns.lineplot(x='yq',y='Value2', data=dataset, hue='Group', ax=ax1, legend = None)
ax1.set_xticklabels(dataset['yq'], rotation=45)
ax1.set_ylabel("")
ax1.set_ylim((0, max(dataset['Value2']) + 0.05))
ax2.set_ylim(0, max(dataset['Value2']) + 0.05)
sns.barplot(x='yq', y='Value1', data=dataset, hue='Group',ax=ax2)

#iterate through each group of bars
for group in ax2.containers:
    for bar in group:
        #label the bar graphs based on the coordinates of the bar patches
        ax2.text(
            bar.get_xy()[0]+bar.get_width()/2,
            bar.get_height(), 
            '{:.1f}%'.format(100*bar.get_height()), 
            color='black',
            horizontalalignment='center'
        )

ax1.yaxis.set_visible(False)
ax2.yaxis.set_visible(False)
ax2.xaxis.set_visible(False)