R 如何创建堆叠线打印
在R中创建堆叠条形图有多种解决方案,但如何绘制堆叠线形图R 如何创建堆叠线打印,r,charts,diagram,R,Charts,Diagram,在R中创建堆叠条形图有多种解决方案,但如何绘制堆叠线形图 如果图表数据作为数据框提供,列中有“线”,行中有Y值,并且row.name是X值,则此脚本使用多边形函数创建堆叠的折线图 stackplot = function(data, ylim=NA, main=NA, colors=NA, xlab=NA, ylab=NA) { # stacked line plot if (is.na(ylim)) { ylim=c(0, max(rowSums(data, na.rm=T))
如果图表数据作为数据框提供,列中有“线”,行中有Y值,并且row.name是X值,则此脚本使用多边形函数创建堆叠的折线图
stackplot = function(data, ylim=NA, main=NA, colors=NA, xlab=NA, ylab=NA) {
# stacked line plot
if (is.na(ylim)) {
ylim=c(0, max(rowSums(data, na.rm=T)))
}
if (is.na(colors)) {
colors = c("green","red","lightgray","blue","orange","purple", "yellow")
}
xval = as.numeric(row.names(data))
summary = rep(0, nrow(data))
recent = summary
# Create empty plot
plot(c(-100), c(-100), xlim=c(min(xval, na.rm=T), max(xval, na.rm=T)), ylim=ylim, main=main, xlab=xlab, ylab=ylab)
# One polygon per column
cols = names(data)
for (c in 1:length(cols)) {
current = data[[cols[[c]]]]
summary = summary + current
polygon(
x=c(xval, rev(xval)),
y=c(summary, rev(recent)),
col=colors[[c]]
)
recent = summary
}
}
可以使用
ggplot2
软件包创建堆叠线图
一些示例数据:
set.seed(11)
df <- data.frame(a = rlnorm(30), b = 1:10, c = rep(LETTERS[1:3], each = 10))
只需在
geom\u行(position=“stack”)
中指定position=“stack”
。例如:
dat <- data.frame(x = c(1:5,1:5),
y = c(9:5, 10,7,5,3,1),
type = rep(c("a", "b"), each = 5))
library(dplyr)
library(ggplot2)
dat %>%
ggplot(aes(fill = type,
x = x,
y = y,
color = type,
linetype = type)) +
geom_line(position = "stack", size = 2) + # specify it here
theme_bw()
许多用户似乎在搜索堆叠条形图时发现了这个问题。查看此处:建议的调整:将
…
添加到参数列表中,以便所有绘图
功能参数都可用。特别是,xaxs=“i”
将消除堆叠图形和绘图边缘之间的空白。
dat <- data.frame(x = c(1:5,1:5),
y = c(9:5, 10,7,5,3,1),
type = rep(c("a", "b"), each = 5))
library(dplyr)
library(ggplot2)
dat %>%
ggplot(aes(fill = type,
x = x,
y = y,
color = type,
linetype = type)) +
geom_line(position = "stack", size = 2) + # specify it here
theme_bw()
dat %>%
ggplot(aes(fill = type,
x = x,
y = y,
color = type,
linetype = type)) +
geom_area(position="stack",
stat="identity",
alpha = 0.5) +
geom_line(position = "stack", size = 2) +
theme_bw()