我有以下数据表:
dt.data <- structure(list(yyyymm= c("2024-04", "2024-04", "2024-04",
"2024-04", "2024-04", "2024-04", "2024-04", "2024-04", "2024-04",
"2024-04", "2024-04", "2024-04", "2024-04", "2024-04", "2024-05",
"2024-05", "2024-05", "2024-05", "2024-05", "2024-05", "2024-05",
"2024-05", "2024-05", "2024-05", "2024-05", "2024-05", "2024-05",
"2024-05", "2024-06", "2024-06", "2024-06", "2024-06", "2024-06",
"2024-06", "2024-06", "2024-06", "2024-06", "2024-06", "2024-06",
"2024-06", "2024-06", "2024-06", "2024-07", "2024-07", "2024-07",
"2024-07", "2024-07", "2024-07", "2024-07", "2024-07"), value = c(0,
-23760, 720, 720, -13680, 18252, -2160, 3600, 6552, -1420.56,
20534.4, 2160, 5040, 1980, 0, -24552, 744, 744, -4464, 18860.4,
-2232, 3720, 10490.4, -1467.91, 15266.88, 2232, 5208, 2046, 0,
-23760, 720, 720, -720, 18252, -2160, 3600, 10152, -1420.56,
11174.4, 2160, 5040, 1980, 0, -24552, 744, 744, -744, 18860.4,
-2232, 3720), testComp = c("Axpo (CH)", "CEZ (CZ)", "EDF Trading (GB)",
"Energie AG (AT)", "Energie Klagenfurt (AT)", "Engie (FR)", "HSE (SI)",
"Mercuria (CH)", "OMV Gas M&T (AT)", "RAG (AT)", "RWE (DE)",
"RWE (GB)", "SEFE (GB)", "WINGAS (DE)", "Axpo (CH)", "CEZ (CZ)",
"EDF Trading (GB)", "Energie AG (AT)", "Energie Klagenfurt (AT)",
"Engie (FR)", "HSE (SI)", "Mercuria (CH)", "OMV Gas M&T (AT)",
"RAG (AT)", "RWE (DE)", "RWE (GB)", "SEFE (GB)", "WINGAS (DE)",
"Axpo (CH)", "CEZ (CZ)", "EDF Trading (GB)", "Energie AG (AT)",
"Energie Klagenfurt (AT)", "Engie (FR)", "HSE (SI)", "Mercuria (CH)",
"OMV Gas M&T (AT)", "RAG (AT)", "RWE (DE)", "RWE (GB)", "SEFE (GB)",
"WINGAS (DE)", "Axpo (CH)", "CEZ (CZ)", "EDF Trading (GB)", "Energie AG (AT)",
"Energie Klagenfurt (AT)", "Engie (FR)", "HSE (SI)", "Mercuria (CH)"
)), row.names = c(NA, -50L), class = c("data.table", "data.frame"
))
我想创建一个堆积条形图,其中 y 轴描述每个
value
的 testComp
,x 轴描述列 yyyymm
。
我该怎么做?
我想要
testComp
的图例以及每个 testComp
的不同颜色。
此外,如果我可以自定义悬停模式,那就太好了。
给你的数据框起这个名字
dt.data <- data.table(your datahere)
##使用此代码检查您的数据框
dt.data
##将 yyyymm 列转换为日期格式
dt.data$yyyymm <- as.Date(paste0(dt.data$yyyymm, "-01"))
##绘制堆积条形图##
p<-ggplot(dt.data, aes(x = yyyymm, y = value, fill = testComp)) +
geom_bar(stat = "identity") +
labs(x = "yyyymm", y = "Value", title = "Stacked Bar Chart") +
scale_fill_manual(values = rainbow(length(unique(dt.data$testComp)))) +
theme_minimal() +
theme(legend.position = "right") +
guides(fill = guide_legend(title = "testComp")) +
scale_x_date(date_labels = "%Y-%m", date_breaks = "1 month") +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
theme(plot.title = element_text(hjust = 0.5)) +
theme(legend.key.size = unit(0.7, "cm"))
ggplotly(p, tooltip = c("x", "y", "fill"), hovermode = "x")
喜欢,请勾选正确,如果它适合您,如图中悬停模式所示