ggplot2 Как выровнять графики с равным масштабом y в процентах - PullRequest
0 голосов
/ 16 ноября 2018

Я пытаюсь получить 2 выровненных столбчатых графика с процентной шкалой 2 разных факторов.Шкалы Y, рассчитанные в процентах, отличаются.Я хотел бы иметь одинаковую шкалу y для обоих графиков, например от 0 до 40% на обоих.Я пробовал ylim (), который не работает в процентном масштабе.Пример ниже

library(ggplot2)
library(scales)
data("diamonds")

Первый гистограмма для среза

  p<- ggplot(diamonds, aes(x = cut)) +  
    geom_bar(aes(y = (..count..)/sum(..count..), fill=cut)) + 
    scale_y_continuous(labels = percent) +
    geom_text(aes(y = ((..count..)/sum(..count..)), label = 
    scales::percent((..count..)/sum(..count..))), 
            stat = "count", vjust = -0.25) +
    ggtitle("Cut") + theme(plot.title = element_text(hjust = 0.5, size=14, 
    face="bold")) + 
    xlab("Cut") +
    ylab("Percent") +
    theme(legend.position="bottom")

Второй гистограмма для наглядности

p1<- ggplot(diamonds, aes(x = clarity)) +  
geom_bar(aes(y = (..count..)/sum(..count..), fill=clarity)) + 
scale_y_continuous(labels = percent) +
geom_text(aes(y = ((..count..)/sum(..count..)), label = 
scales::percent((..count..)/sum(..count..))), 
        stat = "count", vjust = -0.25) +
ggtitle("Clarity") + theme(plot.title = element_text(hjust = 0.5, size=14, 
face="bold")) + 
xlab("Clarity") +
ylab("Percent") +
theme(legend.position="bottom")

Организация гистограммы с разными масштабами

  grid.arrange(p,p1, ncol = 2)  

разные шкалы, но я хотел бы, например, на вершине 40%

enter image description here

Если бы шкалы не были процентами, я бы сделалэто:

p<- ggplot(diamonds, aes(x = cut)) +  
  geom_bar(aes(y = (..count..)/sum(..count..), fill=cut)) + 
  scale_y_continuous(labels = percent) +
  geom_text(aes(y = ((..count..)/sum(..count..)), label = scales::percent((..count..)/sum(..count..))), 
            stat = "count", vjust = -0.25) +
  ggtitle("Cut") + theme(plot.title = element_text(hjust = 0.5, size=14, face="bold")) + 
  xlab("Cut") +
  ylab("Percent") +
  ylim(0, 40)
  theme(legend.position="bottom")

Но здесь, конечно, это не работает и возвращает это:

enter image description here

1 Ответ

0 голосов
/ 16 ноября 2018

Хорошо, я нашел способ, здесь код для Cut для шкалы%, ограниченный 60%

p<- ggplot(diamonds, aes(x = cut)) +  
  geom_bar(aes(y = (..count..)/sum(..count..), fill=cut)) + 
  geom_text(aes(y = ((..count..)/sum(..count..)), label = scales::percent((..count..)/sum(..count..))), 
            stat = "count", vjust = -0.25) +
  ggtitle("Diamonds Cut") + theme(plot.title = element_text(hjust = 0.5, size=14, face="bold")) + 
  scale_y_continuous(labels = scales::percent, limits=c(0,0.6)) + labs(y="Percent")
xlab("Cut") +
  theme(legend.position="bottom")
p

enter image description here

...