【问题标题】:ggplot2 date in X axis is all combinedX轴上的ggplot2日期全部合并
【发布时间】:2019-10-26 17:10:10
【问题描述】:

我是闪亮的新手,我创建了一个应用程序,但是由于我的数据集很大,我的所有日​​期字段都被压缩在一起,用户无法读取,我想尝试绘制所选年份(2014 年)的每个特定日期以及与该日期、选定年份和国家/地区相关联的每个特定价格,但如果不在 csv 文件中组合我不想这样做的日期/年份,我似乎无法轻松做到这一点。

GGPLOT 示例:

我尝试过使用如下所示的 aes 代码,但即使将日期字段分配给 y 轴,也会发生同样的事情。

 library(shiny)
 library(ggplot2)
 pigs <- read.csv("pigs_data.csv")
 # Define UI for application 
 ui <- fluidPage(
 # Application title
 titlePanel("Pig Breeding"),
 sidebarLayout( 
 sidebarPanel(
 #Allows user to choose a year which changes the distribution of plot points
 selectInput(inputId = "year",
            label = "Choose a year:",
            choices = c(2014, 2015, 2016, 2017, 2018),
            selectize = FALSE
            )
 ),
 # Show a plot of the generated distribution
 mainPanel(
 plotOutput("stats")
 )
  )
   )
 # Define server logic
 server <- function(input, output) { #for the selectInput you can use the following observeEvent(input$year, {
 output$stats <- renderPlot({
                    ggplot(pigs, 
                    aes(x = price, y = date, col = country)) + 
                    geom_jitter(width = 0.3) +
                    facet_grid(. ~input$year)
 })
 }
 # Run the application 
 shinyApp(ui = ui, server = server)'

我希望该应用程序显示每个选定年份 (2014 年) 的单独日期 (23/04/14) 以及分配给每个国家/地区的特定价格 (123.40) 的情节点,即使这意味着过度绘图。

数据集示例:

【问题讨论】:

  • 它被压扁了,因为“日期”列不是日期
  • csv 文件或绘图的 aes 编码中的日期列?
  • 检查这个 - stackoverflow.com/questions/4310326/…,我也会使用geom_line,因为有多个组并且它是连续的

标签: r ggplot2 shiny


【解决方案1】:

您的日期列仍然是一个字符串。为了解决它,您可以尝试以下方法

pigs <- read.csv("pigs_data.csv") pigs$date <- as.Date(pigs$date, format="%d-%b-%y")

获取您的字符串并将其转换为日期列。

【讨论】:

  • 嗨,Thomas,我收到此代码错误:错误:'to' must be afinite number
  • 我的猜测是,在将字符串转换为日期格式时引入了 NA。如果缩写与您的本地 r 安装不匹配,则可能会发生这种情况。您可以调用以下代码并将输出发送给我吗? dput(pigs[1:5,]) 它创建与数据对应的 r 代码。这样我可以将它读入我的 r 会话中,看看我是否可以重现错误。
  • 调用此代码时出现以下错误:> dput(pigs[1:5,]) Error in dput(pigs[1:5, ]) : object 'pigs' not found
  • structure(list(country = structure(c(5L, 5L, 5L, 5L, 5L), .Label = c(“丹麦”、“欧盟其他”、“法国”、“德国” , "意大利", "波兰", "西班牙", "英国"), class= "因素"), 日期 = 结构(c(NA_real_, NA_real_, NA_real_, NA_real_, NA_real_), class= "日期"), 价格= c(75.51, 76.45, 77.82, 78.33, 78.78)), row.names = c(NA, 5L), class= "data.frame")
  • 所以格式与我预期的不同。某些程序(例如 excel)将日期更改为更易读的格式。这应该工作。 pigs$date
猜你喜欢
  • 1970-01-01
  • 2012-07-29
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多