首页 > 解决方案 > ggplot2 R 图表

问题描述

我是 R 新手,从基本情节开始。我使用了一个简单的 excel 表,其中包含以下列 - Family、Family Name、Product.ID、Sales、Time、Value

该表类似于下面的快照

样本数据

我使用了下面的代码,但由于某种原因,当我尝试按姓氏对图表进行分组时,它只显示一种颜色,甚至家族名称中的所有值都没有出现图例

library("ggplot2")
library("data.table")
library("readxl")
Data<-read.xlsx("C:/Users/vc/Desktop/Sales Data.xlsx")
setDT(Data)
Plot<-ggplot(data = Data,
             aes(x=Time,y=Value,group='Family Name',shape='Family Name',color='Family Name')) +
  geom_line() + 
  geom_point()

我附上了输出图,它没有任何意义。

输出图

标签: rggplot2data-visualization

解决方案


你想要这个吗?

  • 要在 x 轴上描述日期,您需要将变量转换为as.Date()第一个
library(tidyverse)
df <- data.frame(
  stringsAsFactors = FALSE,
            Family = c("19A", "19A", "19A", "19A", "19B", "19B", "19B", "19B"),
       Family.Name = c("A Box","A Box","A Box",
                       "A Box","B Box","B Box","B Box","B Box"),
        Product.ID = c("AA980","AA980","AA980",
                       "AA980","AL345","AL345","AL345","AL345"),
             Sales = c("actualsalesunit",
                       "actualsalesunit","actualsalesunit","actualsalesunit",
                       "actualsalesunit","actualsalesunit","actualsalesunit",
                       "actualsalesunit"),
             Times = c("01-01-2021","01-02-2021",
                       "01-03-2021","01-04-2021","01-01-2021","01-02-2021",
                       "01-03-2021","01-04-2021"),
             value = c(63L, 34L, 93L, 99L, 1L, 0L, 0L, 0L)
)

df %>%
  mutate(Times = as.Date(Times, '%d-%m-%Y')) %>%
  ggplot(aes(x= Times, y = value, color = Family.Name, label = value)) +
  geom_line() +
  geom_point() +
  geom_text(size = 3.2, position =position_dodge(0.9), vjust = -0.5)

reprex 包于 2021-05-27 创建 (v2.0.0 )


推荐阅读