ggplot2 中的 Y 轴位置

Y axis position in ggplot2

我有一个情节 below. I would like to remove the values in the y-axis and rank. I would like to reshape my plot so it would look more like in the image.

library(ggplot2)
library(dplyr)

df <- data.frame(dose = c("D0.5", "D1", "D2", "D3", "D4", "D5"),
                 len = c(4.2, 10, 29.5, 5, 7, 15))


df <- df |> 
  dplyr::arrange(desc(len)) |>
  dplyr::mutate(
    rank = factor(row_number(), labels = dose)
  )

fill_colors = c("blue", "yellow", "green")
other_colors = rep("grey50", nrow(df)-length(fill_colors))
my_scale  <- c(fill_colors, other_colors)

withr::with_options(
  list(ggplot2.discrete.fill = my_scale),
  ggplot(data = df, aes(x = reorder(dose, len), y = len)) +
    geom_bar(stat = "identity", aes(fill = rank), width = 0.5) +
    scale_fill_discrete() + theme_minimal() +
    xlab("len") + ylab("type") + 
    coord_flip()
)

你在找这个吗?

ggplot(data = df, aes(x = reorder(dose, len), y = len)) +
  geom_bar(stat = "identity", aes(fill = rank), width = 0.5) +
  theme_minimal() +
  xlab("len") + ylab("type") + 
  coord_flip() +
  scale_fill_manual(values = c("#92d050", "#57d3ff", "#ffc000", 
                               rep('#bfbfbf', nrow(df) - 3))) +
  theme(legend.position = 'none', axis.text.y = element_blank())

也许稍有不同的外观也可以,geom_text 在栏的顶部?

我使用了 中的代码来突出显示前三个栏 - 我发现它更短且更易于阅读,并且不再需要对 withr 进行这种冗长的调用。但是,最值得注意的是,我调换了 x 和 y,所以您不再需要 coord_flip。

library(ggplot2)
library(dplyr)

df <- data.frame(dose = c("D0.5", "D1", "D2", "D3", "D4", "D5"),
                 len = c(4.2, 10, 29.5, 5, 7, 15))

## thanks Allan
mycols <- c("#92d050", "#57d3ff", "#ffc000")

## I've used the code from my answer to your previous question, I find it shorter and easier to read
## 
df <- df %>%
  arrange(desc(len)) %>%
  mutate(fills = ifelse(row_number() <= length(mycols), mycols, "grey50"))

ggplot(data = df, aes(x = len, y = reorder(dose, len))) +
  geom_col(aes(fill = I(fills)))+
  geom_text(aes(x = len/2, label = glue::glue("{dose} ({len}%)"))) +
  theme_minimal() +
  ## remove expansion and x title
  scale_x_continuous(NULL, expand = c(0,0)) +
  # remove the y bits
  theme(axis.ticks.y = element_blank(), 
        axis.title.y = element_blank(), 
        axis.text.y = element_blank())

reprex package (v2.0.1)

创建于 2022-05-31