【问题标题】:2d plot with 3rd variable as color in RStudio在 RStudio 中以第三个变量作为颜色的 2d 图
【发布时间】:2018-12-16 18:03:53
【问题描述】:

我有一个包含三列的 CSV 数据集:

  • 时间戳(例如 2018/12/15)
  • 关键字(例如“你好”)
  • 计数(例如 7)

我想要一个图,其中相同关键字的所有行都相互连接,时间戳在 X 轴上,计数在 Y 轴上。我希望每个关键字的行和标有关键字的行具有不同的颜色。

CSV 只有约 30.000 行,R 在专用机器上运行。性能可以忽略。

我在这个论坛中尝试了使用 mathplot 和 ggplot 的各种方法,但没有让它与我自己的数据一起使用。

在 R 中最简单的解决方案是什么?

谢谢!

编辑:

我尝试自定义 Romans 代码并尝试了以下操作:

`csvdata <- read.csv("c:/mydataset.csv", header=TRUE, sep=",")  

time <- csvdata$timestamp  
count <- csvdata$count  
keyword <- csvdata$keyword  

time <- rep(time)  
xy <- data.frame(time, word = c(keyword), count, lambda = 5)  

library(ggplot2)  

ggplot(xy, aes(x = time, y = count, color = keyword)) +  
  theme_bw() +  
  scale_color_brewer(palette = "Set1") +  # choose appropriate palette  
  geom_line()`

这会创建一个正确的画布,但其中没有点/线...

数据:

头部(csvdata)

keyword count  timestamp
1 non-distinct-word     3 2018/08/09
2 non-distinct-word     2 2018/08/10
3 non-distinct-word     3 2018/08/11

str(csvdata)

'data.frame':   121 obs. of  3 variables:
 $ keyword  : Factor w/ 10 levels "non-distinct-word",..: 5 5 5 5 5 5 5 5 5 5 ...
 $ count    : int  3 2 3 1 6 6 2 3 2 1 ...
 $ timestamp: Factor w/ 103 levels "2018/08/09","2018/08/10",..: 1 2 3 4 5 6 7 8 9 10 ...

【问题讨论】:

  • 我建议你提供一个reproducible的问题。这包括示例代码(包括列出非基础 R 包)和示例数据(例如,dput(head(x)))。显示您尝试过的代码并说明它们为什么不正确是一个非常好的步骤。参考:stackoverflow.com/questions/5963269stackoverflow.com/help/mcvestackoverflow.com/tags/r/info
  • 您是否考虑过将timestamp 强制转换为正确的Date 对象?试试as.Date(as.character(csvdata$timestamp), format = "%Y-%m-%d)
  • 如果我这样做,它会抛出 Error in seq.int(0, to0 - from, by) : 'to' cannot be NA, NaN or infinite。我目前的解决方法是我转换为 as.Numeric,它可以工作,但不能正确显示时间戳轴(只显示数字),所以我截图并在 photoshop 中添加轴...

标签: r data-visualization


【解决方案1】:

这样的?

# Generate some data. This is the part poster of the question normally provides.
today <- as.Date(Sys.time())
time <- rep(seq.Date(from = today, to = today + 30, by = "day"), each = 2)
xy <- data.frame(time, word = c("hello", "world"), count = rpois(length(time), lambda = 5))

library(ggplot2)

ggplot(xy, aes(x = time, y = count, color = word)) +
  theme_bw() +
  scale_color_brewer(palette = "Set1") +  # choose appropriate palette
  geom_line()

【讨论】:

  • Roman,非常感谢您的回复:我知道这可能是一个菜鸟问题。我从 CSV 加载数据并使用您的代码进行尝试。 (我无法在评论中添加它,所以我更新了原始问题)。我加载了画布,但没有填充任何点或线。我的方法有明显的问题吗?再次感谢,我知道您的时间非常宝贵!
  • @to_the_nth 请显示您的数据是什么样的。您可以使用headstr 函数。
猜你喜欢
  • 1970-01-01
  • 2012-01-02
  • 2017-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-19
  • 2016-10-23
  • 1970-01-01
相关资源
最近更新 更多