Ani*_*ali 3 graphics charts r data-visualization ggplot2
我想提供以下数据
x <- factor(c(1,2,3,4,5))
x
[1] 1 2 3 4 5
Levels: 1 2 3 4 5
value <- c(10,5,7,4,12)
value
[1] 10 5 7 4 12
y <- data.frame(x, value)
y
x value
1 1 10
2 2 5
3 3 7
4 4 4
5 5 12
Run Code Online (Sandbox Code Playgroud)
我想将上述信息转换为以下图形表示
上面描述的图形类型是什么?我检查了点图,但只是垂直堆叠.
该解决方案绘制了由三个条形图组成的集合x
.使用除以value
3 的余数确定每组内的条的高度.水平间距由自然的间距提供.使用白色网格线创建垂直间距.
library(ggplot2)
library(reshape2)
Run Code Online (Sandbox Code Playgroud)
dataset <- data.frame('x' = 1:5, 'value' = c(10, 5, 7, 4, 12))
Run Code Online (Sandbox Code Playgroud)
由于每个value
应该由三个条形表示,我们将向数据集添加3列,并value
使用整数除法分配其中的大小:
dataset[, c('col1', 'col2', 'col3')] <- floor(dataset$value / 3)
r <- dataset$value %% 3
dataset[r == 1, 'col1'] <- dataset[dataset$value %% 3 == 1, 'col1'] + 1
dataset[r == 2, c('col1', 'col2')] <- dataset[r == 2, c('col1', 'col2')] + 1
Run Code Online (Sandbox Code Playgroud)
现在,为了绘图,我们将融合数据框:
dataset <- melt(dataset, id.vars = c('x', 'value'))
colnames(dataset)[4] <- 'magnitude' # avoiding colnames conflict
dataset$variable <- as.character(dataset$variable) # column ordering within a facet
Run Code Online (Sandbox Code Playgroud)
首先,我们将制作一个常规条形图.我们可以使用switch
参数将构面标签移动到绘图区域的底部.
plt <- ggplot(data = dataset)
plt <- plt + geom_col(aes(x=variable, y = magnitude), fill = 'black')
plt <- plt + facet_grid(.~x, switch="both")
Run Code Online (Sandbox Code Playgroud)
然后我们将使用theme_minimal()
并添加一些调整来控制网格线的外观.具体来说,我们将确保次要XY网格线和主要X网格线为空白,而主要Y网格线为白色并绘制在数据之上.
plt <- plt + theme_minimal()
plt <- plt + theme(panel.grid.major.x = element_blank(),
panel.grid.major.y = element_line(colour = "white", size = 1.5),
panel.grid.minor = element_blank(),
panel.ontop = TRUE)
Run Code Online (Sandbox Code Playgroud)
我们可以value
使用添加标签geom_text()
.我们只会使用记录中的x
值,col2
这样我们就不会在每个集合中的每个条形图上绘制值(col2
恰好是中间条).
plt <- plt + geom_text(data = dataset[dataset$variable == 'col2', ],
aes(label = value, x = variable, y = magnitude + 0.5))
plt <- plt + theme(axis.text.x=element_blank()) # removing the 'col' labels
plt + xlab('x') + ylab('value')
Run Code Online (Sandbox Code Playgroud)