График с накоплением Ggplot2 с 1200 значениями - PullRequest
0 голосов
/ 02 июня 2018

Привет, ggplot2 warriors!

Я борюсь с составным графиком, который содержит около 1200 значений стеков.У меня есть df с 4 переменными

'data.frame':   4935 obs. of  4 variables:
 $ ISO3   : Factor w/ 133 levels "AGO","ALB","ARE",..: 23 105...
 $ band   : int  1 1 1 2 1 1 1 2 1 1 ...
 $ upbound: num  1000 1000 1000 2000 1000 1000 1000 2000 1000 1000 ...
 $ ET1    : num  3981 1280 1223 1096 772 ...

Мне нужно построить график страны (ISO3) против ET1, сгруппированных по полосам.

Код:

library(dplyr); library(ggplot2); library(scales); library(ggsci); library(gridExtra); library(RColorBrewer); library(tidyr); library(reshape2)

#df
ex1 <- read.csv("example.csv")
ET <- select(ex, ET1) # used later 
ex <-  ex1  %>%  # to get descent values and graph according 
  arrange(desc(ET1, na.rm = TRUE))

#ex graph 
ggplot(data = ex) + 
  geom_bar(mapping = aes(x = ISO3, fill = as.factor(upbound))) + #use as.factor to stack (correct?)
  theme(legend.position="none", text=element_text(size=25)) + # none because there are 1200 values in legend
  xlab("Country") + ylab("ET1") +
  coord_flip() + #tested up to here # save 1500x4000
  #scale_fill_continuous(aes(as.numeric(upbound)),breaks = c(500, 1000)) + #doesn't work
  #scale_x_log10(minor_breaks = log10(ET)) +#doesn't work

Здесь ex graph ex

#ex_a graph
ggplot(data = ex) + 
  geom_bar(mapping = aes(x = ISO3, fill = as.factor(upbound))) +
  theme(legend.position="bottom", text=element_text(size=25)) +
  xlab("Country") + ylab("ET1") +
  coord_flip() # save 1500x10000

#one solution could be 
#scale_fill_continuous(aes(as.numeric(band)),breaks = c(500, 1000)) # band instead of upbound # doesn’t work neither 

Здесь ex_a graph ex_a

Проблемы: 1. Значения не соответствуют ожидаемым.2. Цвет для 1200 суммированных значений не визуализируется красиво.3. Стеки должны быть сделаны группой вместо восходящей.4. Чтобы иметь лучшую визуализацию, я думаю, чтобы иметь масштаб журнала для ET1, но не работает ни.5. После переворота на графике должна быть страна против ЕТ1, а не страна против восходящей.

Вот воспроизводимый пример: пример

Я был бы очень признателен за любую помощь.

1 Ответ

0 голосов
/ 04 июня 2018

Я не уверен, что это результат, который вы ищете для своего вопроса 1. Дайте мне знать через комментарий, если я ошибаюсь.Но я сделал вывод, что вы хотите отсортировать ось x по числу случаев, которые есть у каждого ISO3.Здесь я делаю большое предположение, которое может быть неверным, что вы хотите, чтобы ось X была отсортирована по наибольшему значению ET1 среди всех наблюдений с общим значением ISO3.

 library(tidyverse)

 ex1 %>% 
 group_by(ISO3) %>% 
 mutate(ET1_sort = max(ET1)) %>% ## Create a value through which to sort the x axis in the geom_bar()
 ggplot() +
 geom_bar(aes(x = reorder(ISO3, X = ET1_sort), ## Sort here, through reorder
          fill = as.factor(upbound))) + #use as.factor to stack (correct?) //R I think so
 theme(legend.position="none") + # none because there are 1200 values in legend
 xlab("Country") + 
 ylab("ET1") + ## Watch out, this might or might not be representative of ET1. The stack is a sum of observations, which does not necesarily reflect the ET1 values from your df. Again, check if this is true or not.
 coord_flip()

Результаты:

The Figure

В качестве альтернативы, здесь я сортирую количество наблюдений.Это еще одно большое предположение.

ex1 %>%
group_by(ISO3) %>%
mutate(ET1_sort = n()) %>% ## Create a value through which to sort the x axis in the geom_bar()
ggplot() +
geom_bar(aes(x = reorder(ISO3, X = ET1_sort), ## Sort here, through reorder
             fill = as.factor(upbound))) + #use as.factor to stack (correct?) //R I think so
theme(legend.position="none") + # none because there are 1200 values in legend
xlab("Country") + 
ylab("ET1") + ## Watch out, this might or might not be representative of ET1. The stack is a sum of observations, which does not necesarily reflect the ET1 values from your df. Again, check if this is true or not.
coord_flip()

Results2:

Results2

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...