如何在 R 中为 y_continuous 设置 ylim?

How to set the ylim for y_continuous in R?

我是 R 的新手,我想知道如何在 R 中设置 scale_y_continuous 的限制百分比。我想将 ylim btw 0% 设置为 40%,但它不起作用:(

这是我的代码:

library(ggplot2)
library(scales)
dat <- data.frame(
  time = factor(c("Breakfast","Lunch","Lunch","Dinner"), levels=c("Breakfast","Lunch","Dinner")),
  total_bill = c(12.75,14.89,"*",17.23)
)
#clear the * row and save the new dataframe
dat1 <- droplevels(subset(dat, total_bill != "*"))
dat1 <- type.convert(dat1, as.is = TRUE)

# add a column for percent of total bill
dat1$perc <- ((dat1$total_bill)/sum(dat1$total_bill)) * 100

# example plot with some minimal formatting
ggplot(dat1, aes(time,perc)) +
  geom_bar(aes(y=perc),stat="identity",fill = "#4B0082") +
  geom_text(aes(label = scales::percent(perc),y=perc),
            vjust=.5,hjust=1.2,color="white")+
  scale_y_continuous(labels = scales::percent,limits = c(0,40))+
  labs(title="x",y="%")+
  coord_flip()

如有任何帮助,我们将不胜感激

有几件事,比例尺以百分比显示面积比例的数字,因此无需乘以 100。然后将 40% 的限制设置为 c(0,0.4):

    library(ggplot2)
  library(scales)
  dat <- data.frame(
    time = factor(c("Breakfast","Lunch","Lunch","Dinner"), levels=c("Breakfast","Lunch","Dinner")),
    total_bill = c(12.75,14.89,"*",17.23)
  )
  #clear the * row and save the new dataframe
  dat1 <- droplevels(subset(dat, total_bill != "*"))
  dat1 <- type.convert(dat1, as.is = TRUE)

  # add a column for percent of total bill
  dat1$perc <- ((dat1$total_bill)/sum(dat1$total_bill))

  # example plot with some minimal formatting
  ggplot(dat1, aes(time,perc)) +
    geom_bar(aes(y=perc),stat="identity",fill = "#4B0082") +
    geom_text(aes(label = scales::percent(perc),y=perc),
              vjust=.5,hjust=1.2,color="white")+
    scale_y_continuous(labels = scales::percent,limits = c(0,0.4))+
    labs(title="x",y="%")+
    coord_flip()