如何在R中为y_continuous设置ylim?

问题描述 投票:0回答:1

我是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()

任何帮助将不胜感激

r ggplot2 percentage geom-bar
1个回答
2
投票

有两件事,比例尺显示的数字占一定比例的百分比,因此无需乘以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()
© www.soinside.com 2019 - 2024. All rights reserved.