如何使用ggplot在Shiny中使用相同的配色方案制作图形?

时间:2019-03-06 17:16:58

标签: r ggplot2 shiny

我正在尝试制作具有两个图形的Shiny应用程序:

1)第一张包含每个公司销售额的图表,

2)排名第二的顶级品牌

我希望第二张图中的品牌颜色与第一张图中所拥有的公司的颜色相同。我找到了一个使用R可以完成的示例,但是不知道如何在Shiny中复制它。

我不知道如何制作带有响应元素的命名向量names(myColors) <- levels(dat$grp)

下面的示例代码和R的进一步解决方案。

library(shiny)
library(dplyr)
library(ggplot2)

ui <- fluidPage(
# slider that limits number of corporations for which the brands are shown
sliderInput(inputId = "n_corpo",
          label = "Number of corporations",
          value = 2, min = 1, max = 5, step= 1),

plotOutput("corpo"), # first graph
plotOutput("brands") # second graph
)

server <- function(input, output, session) {
# creating data frame 
brand <- data.frame(brand= rep(LETTERS[6:15],each = 3),stringsAsFactors = FALSE,
                  period = sample(1:10),
                  value = runif(10))

corporation <- data.frame(corpo = rep(LETTERS[1:5],each = 2),stringsAsFactors = FALSE,
                        brand = LETTERS[6:15]) %>%
                        left_join(brand, .)

# code to create first graph
output$corpo = renderPlot({
  corporation %>%
  group_by(corpo, period) %>%
  summarise(value = sum(value))%>%
  ggplot(aes(period, value, fill = corpo))+
  geom_col()+
  facet_wrap(~corpo)
  })

# code for the second graph
output$brands = renderPlot({


# selecting n biggest corporations 
corpo_top_n = corporation %>%
  group_by(corpo) %>%
  summarise(value = sum(value)) %>%
  top_n(input$n_corpo, value) %>%
  select(corpo)

# graph with the brands of selected corporations
corporation %>%
  group_by(corpo, brand, period) %>%
  summarise(value = sum(value))%>%
  inner_join(., corpo_top_n) %>%
  ggplot(aes(period, value, fill = corpo))+
  geom_col()+
  facet_wrap(~brand)
  })
 }

shinyApp(ui, server)

我找到了此解决方案,但无法使其与Shiny一起使用。

#Some test data
dat <- data.frame(x=runif(10),y=runif(10),
              grp = rep(LETTERS[1:5],each = 2),stringsAsFactors = TRUE)

#Create a custom color scale
library(RColorBrewer)
myColors <- brewer.pal(5,"Paired")
colScale <- scale_colour_manual(name = "grp",values = myColors)

names(myColors) <- levels(dat$grp) # this part do not know how to adapt to Shiny
colScale <- scale_colour_manual(name = "grp",values = myColors)


 #One plot with all the data
 p <- ggplot(dat,aes(x,y,colour = grp)) + geom_point()
 p1 <- p + colScale

 #A second plot with only four of the levels
 p2 <- p %+% droplevels(subset(dat[4:10,])) + colScale

谢谢您的帮助! 马雷克

0 个答案:

没有答案