我无法理解为什么我的 ggplot 第一个条形标签一半隐藏在下面的水平条形图中。
我不想减小标签的尺寸,因为它们看起来太小。我尝试添加边距,但无济于事。
你能帮我吗?
# Import dataset
db <- read_excel("dataset.xlsx")
options(scipen = 999)
# Rename variables
colnames(db) <- c("rank",
"name",
"sport",
"totalEarnings",
"on-the-field_Earnings",
"off-the-field_Earnings")
# Format numbers
custom_number_format <- function(x){ifelse(x > 999999,paste(format(round((x/1000000))),"M"),format(round(x)))}
# Create text column in dataset to display the tooltip
db <- db %>%
mutate(text = paste(
"<span style='font-size:14px;'><b>", name, "</b></span><br>",
"\nOn Field Earnings:", "<b> $", custom_number_format(`on-the-field_Earnings`), "</b>",
"\nOff Field Earnings:", "<b> $",custom_number_format(`off-the-field_Earnings`), "</b><br>",
"<span style='font-size:16px;'> \nTotal Earnings:</span>", "<b> $", custom_number_format(totalEarnings), "</b>"))
# Design Bar chart
ggp <- db %>%
mutate(name = fct_reorder(name, totalEarnings)) %>%
ggplot(aes(totalEarnings, name, fill = totalEarnings, text = text)) +
geom_col(width = 0.7, show.legend = FALSE) +
scale_x_continuous(limits=c(0, 160000000), expand = c(0, 0)) +
scale_y_discrete(expand = expansion(mult = 0, 0.05)) +
scale_fill_gradient(high = "#24336a", low = "#2296cf") +
theme(
plot.background = element_blank(),
panel.background = element_blank(),
axis.title = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
axis.ticks.y = element_blank()
) +
geom_text(aes(label = custom_number_format(totalEarnings)), size = 3)
ggp <- ggplotly(ggp, tooltip = "text") %>%
config(displayModeBar = FALSE)
ggp <- ggp %>%
layout(
hoverlabel = list(bgcolor = "white")
)
ggp$x$data[[44]]$textposition <- "right"
ggp
问题是您为 y 比例设置的小扩展。增加扩展,你应该没问题,例如在下面的代码中,我在 y 尺度的两侧使用了 1 的加法展开式。
使用一些虚假的示例数据:
library(plotly, warn=FALSE)
#> Loading required package: ggplot2
library(forcats)
set.seed(123)
db <- data.frame(
name = sample(c(LETTERS, letters), 43),
totalEarnings = seq(1e5, 136e6, length.out = 43)
)
ggp <- db %>%
mutate(name = fct_reorder(name, totalEarnings)) %>%
ggplot(aes(totalEarnings, name, fill = totalEarnings)) +
geom_col(width = 0.7, show.legend = FALSE) +
scale_x_continuous(limits = c(0, 160000000), expand = c(0, 0)) +
scale_y_discrete(expand = c(0, 1)) +
scale_fill_gradient(high = "#24336a", low = "#2296cf") +
theme(
plot.background = element_blank(),
panel.background = element_blank(),
axis.title = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
axis.ticks.y = element_blank()
) +
geom_text(aes(label = custom_number_format(totalEarnings)), size = 3) +
coord_cartesian(clip = "off")
ggp <- ggplotly(ggp, tooltip = "text") %>%
config(displayModeBar = FALSE)
ggp <- ggp %>%
layout(
hoverlabel = list(bgcolor = "white")
)
ggp$x$data[[44]]$textposition <- "right"
ggp