R:ggplot彩色条形图由符号表示吗?绿色=正,红色=负

我希望调整图表,以使零以下的收益呈红色,而正的收益呈绿色。我在一直困扰的两行代码旁边加了一条注释(问题出在最后几行代码中。其他所有功能都可以正常工作。

library(tidyverse)
library(tidyquant)
library(shiny)

#Stock assignments
stock_1<-'AMZN'
stock_2<-'CMG'
stock_3<-'TSS'  
stock_4<-'FB'
stock_5<-'T'

#Creating Input Boxes for Stocks and Weights of the Portfolio
ui <- fluidPage(
  titlePanel('Portfolio Daily Returns'),sidebarLayout(
    sidebarPanel(
      fluidRow(
        column(6,textInput("S1",h3('Input Stock 1'),stock_1)),column(6,numericInput("w1",h3("Input Weight 1"),.25))
      ),fluidRow(
        column(6,textInput("S2",h3('Input Stock 2'),stock_2)),numericInput("w2",h3("Input Weight 2"),textInput("S3",h3('Input Stock 3'),stock_3)),numericInput("w3",h3("Input Weight 3"),.2))
      ),textInput("S4",h3('Input Stock 4'),stock_4)),numericInput("w4",h3("Input Weight 4"),textInput("S5",h3('Input Stock 5'),stock_5)),numericInput("w5",h3("Input Weight 5"),.1))
      ),dateRangeInput("D",h3("Input Start and End Dates"),'2019-09-01',Sys.Date())
    ),mainPanel(plotOutput("plot"))
  )
)
server <- function(input,output){
  dataInput <- reactive({
    tq_get(c(input$S1,input$S2,input$S3,input$S4,input$S5),from=input$D[1],to=input$D[2])%>%
      group_by(symbol)%>%
      tq_transmute(select=volume,mutate_fun = periodReturn,period='daily',col_rename = 'Daily_Vol')%>%
      tq_portfolio(assets_col=symbol,returns_col = Daily_Vol,weights=c(
        input$w1,input$w2,input$w3,input$w4,input$w5),col_rename = 'Port_Vol')
  })

  dataInput[["sign"]] = ifelse(dataInput[["value"]] >= 0,"positive","negative") #Problem
  output$plot <- renderPlot({
    ggplot(dataInput(),aes(x=date,y=Port_Vol))+geom_col()+
      scale_fill_manual(values = c("positive"="green","negative"=red)) #Problem 2
  })
}

shinyApp(ui=ui,server=server)```
gdfg3ggf 回答:R:ggplot彩色条形图由符号表示吗?绿色=正,红色=负

问题1:dataInput是一个反应对象。您应该始终使用dataInput()对其进行调出,并且不能对其进行更改。您可以在绘图时对其进行变异,也可以在返回之前简单地添加到data.frame中。所以我在dataInput调用中添加了正/负

问题2:您需要引用“红色”。另外,您还需要在es中指定fill = sign

在下面我已经编辑了您的服务器功能,它应该可以工作,并且有一些关于NA的警告消息,并且我对Zoo功能不那么熟悉,所以我让您整理一下

server <- function(input,output){
  dataInput <- reactive({
    dat <- tq_get(c(input$S1,input$S2,input$S3,input$S4,input$S5),from=input$D[1],to=input$D[2])%>%
      group_by(symbol)%>%
      tq_transmute(select=volume,mutate_fun = periodReturn,period='daily',col_rename = 'Daily_Vol')%>%
      tq_portfolio(assets_col=symbol,returns_col = Daily_Vol,weights=c(
        input$w1,input$w2,input$w3,input$w4,input$w5),col_rename = 'Port_Vol')
    dat$sign = ifelse(dat$Port_Vol >= 0,"positive","negative")
    return(dat)
  })

  output$plot <- renderPlot({
    ggplot(dataInput(),aes(x=date,y=Port_Vol,fill=sign))+geom_col()+
      scale_fill_manual(values = c("positive"="green","negative"="red")) #Problem 2
  })
}
本文链接:https://www.f2er.com/3131230.html

大家都在问