我正在使用 R 中的 ggplot 包创建一个绘图,但是最后我需要一个绘图对象,因此我应用了 ggplotly 函数。不幸的是,此步骤更改了条形标签的 y 位置。我可以改变什么来防止这种情况发生(或者稍后使用plotly修复)?
# initiate dataframe
my_data <- data.frame(type = c("friendly", "friendly", "friendly","friendly"),
gender = c("male", "female", "male", "female"),
level = c(1,1,2,2),
percent_change =c(10, 11, 9, 8))
# save the x variable
x_var <- unique(my_data$type)
# create the plot - with bar labels
gg <- ggplot(my_data) +
geom_bar(aes(x = x_var, y = percent_change, fill = factor(level)),
stat = 'identity', position = position_dodge(width = 1)) +
geom_text(aes(x = x_var, y = percent_change, label = percent_change, group = interaction(x_var, level)),
position = position_dodge(width = 1), vjust = -0.5) +
scale_fill_manual(values = c("#154273", "#e17000", "#39870c")) +
facet_wrap(~gender)
# transform to plotly object (messes up the labels!)
final_plot <- ggplotly(gg)
我已经尝试使用随后的plotly和textposition进行纠正,但没有成功。
根据我对
plotly
或 ggplotly()
如何工作的理解, vjust
参数没有效果或不会传递给 plotly
对象,很可能是因为 plotly
中没有这样的参数或属性。相反,当使用 plotly
时,文本的位置是通过 textposition
属性设置的,即您可以通过将 textposition=
设置为 "top"
来解决您的问题并将标签放置在条形顶部,以添加跟踪标签。在您的情况下,这些是迹线 5 和 6:
# initiate dataframe
my_data <- data.frame(
type = c("friendly", "friendly", "friendly", "friendly"),
gender = c("male", "female", "male", "female"),
level = c(1, 1, 2, 2),
percent_change = c(10, 11, 9, 8)
)
# save the x variable
x_var <- unique(my_data$type)
library(plotly, warn = FALSE)
#> Loading required package: ggplot2
gg <- ggplot(my_data) +
geom_bar(aes(x = x_var, y = percent_change, fill = factor(level)),
stat = "identity", position = position_dodge(width = 1)
) +
geom_text(
aes(
x = x_var, y = percent_change, label = percent_change,
group = interaction(x_var, level)
),
position = position_dodge(width = 1), vjust = -0.5
) +
scale_fill_manual(values = c("#154273", "#e17000", "#39870c")) +
facet_wrap(~gender)
ggp <- ggplotly(gg)
for (i in 5:6) {
ggp$x$data[[i]]$textposition <- "top"
}
ggp