簡體   English   中英

在r中具有多個y軸變量的圖

[英]Plot graph with multiple y axis variable in r

我有以下數據結構 在此處輸入圖片說明 我繪制了日期(x軸)與TypeA / TypeB /…的關系圖。
如何繪制日期(x軸)與多個類型(如TypeA,TypeB-2行,每行一條)。

當前使用的代碼是

output$trendPlot1 <- renderPlotly({
    dataset1 <- reactive({
      data3[sample(nrow(data3) , 100 ),]
    })
    p <- ggplot(dataset1(), aes_string(x = "Date", y = input$y )) +
       ggtitle(paste0("Simple Cumulative Return of Stock over Time")) +
      # geom_point()
      geom_line()
    ggplotly(p) %>% 
      layout( autosize=TRUE)
  })

用戶在屏幕上輸入y(具有不同類型的下拉列表)。我將具有多個選擇下拉列表,並且能夠選擇不同的類型。 (實際數據中大約有100種類型)。 我只想繪制用戶選擇的那些類型,而不是其余部分。
如何將多個選擇傳遞給要在單個圖形上繪制的圖形?

我已經從上述答案中提取了樣本數據集。

  1. 將數據從寬格式轉換為長格式,以便可以過濾類型。
  2. 在服務器中進行ggplotting時使用它來對數據進行子集化
library(shiny)
library(tidyverse)

Date <- c("29-Oct-2018", "28-Oct-2018", "27-Oct-2018", "26-Oct-2018")
TypeA <- rnorm(4, 5, 2)
TypeB <- rnorm(4, 5, 3)
TypeC <- rnorm(4, 5, 4)
df <- data.frame(Date = Date, TypeA = TypeA, TypeB = TypeB, TypeC = TypeC)

wide_df <- df %>% gather(Type,Value,2:4)


ui <- fluidPage(


  selectInput(inputId = "type",
              label = "",
              choices = unique(wide_df$Type),
              multiple = TRUE),

  plotOutput("first_plot")

)

server <- function(input, output, session) {

  output$first_plot <- renderPlot({

    wide_df %>% 
      filter(Type %in% input$type) %>% 
    ggplot() +
      geom_point(aes(Date, Value, color = Type))

  })




}

shinyApp(ui, server)

在此處輸入圖片說明

由於未提供實際數據(無法復制圖像),因此我使用了示例數據進行解釋。 您需要使用reshape2包中的melt將數據轉換為長格式的reshape2 下面給出了示例代碼。 根據需要進行修改。

library(ggplot2)
library(reshape2)

Date <- c("29-Oct-2018", "28-Oct-2018", "27-Oct-2018", "26-Oct-2018")
TypeA <- rnorm(4, 5, 2)
TypeB <- rnorm(4, 5, 3)
TypeC <- rnorm(4, 5, 4)
df <- data.frame(Date = Date, TypeA = TypeA, TypeB = TypeB, TypeC = TypeC)

plotdf <- melt(df, id.vars = "Date")
print(ggplot(plotdf, aes(value, Date, colour = variable)) + geom_point() + 
        ggtitle(paste0("Simple Cumulative Return of Stock over Time")) +
        theme(legend.position = "bottom")+
        guides(fill = guide_legend(reverse=TRUE)))

輸出:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM