从R中的两个数值变量创建堆叠直方图可以使用ggplot2包来实现。下面是具体的步骤:
install.packages("ggplot2")
来安装。library(ggplot2)
来加载。ggplot(data = df) +
geom_bar(mapping = aes(x = x), position = "stack") +
geom_bar(mapping = aes(x = y), position = "stack")
labs(title = "堆叠直方图",
x = "变量",
y = "频数",
fill = "变量") +
theme(plot.title = element_text(hjust = 0.5),
axis.text = element_text(size = 12),
legend.title = element_text(size = 12),
legend.text = element_text(size = 12))
print(plot)
完整的代码如下:
library(ggplot2)
df <- data.frame(x = c(1, 2, 3, 4, 5),
y = c(2, 3, 4, 5, 6))
plot <- ggplot(data = df) +
geom_bar(mapping = aes(x = x), position = "stack") +
geom_bar(mapping = aes(x = y), position = "stack") +
labs(title = "堆叠直方图",
x = "变量",
y = "频数",
fill = "变量") +
theme(plot.title = element_text(hjust = 0.5),
axis.text = element_text(size = 12),
legend.title = element_text(size = 12),
legend.text = element_text(size = 12))
print(plot)
该代码将创建一个堆叠直方图,其中x和y变量分别表示两个数值变量。可根据实际情况修改数据框和变量的名称,以及调整其他图表属性来满足需求。
腾讯云相关产品介绍地址:
领取专属 10元无门槛券
手把手带您无忧上云