r - 如何在R中绘制下图?这些类型的图表叫什么?

标签 r ggplot2 charts graphics data-visualization

我正在尝试提供以下数据

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

我想把上面的信息转换成下面的图形表示

enter image description here

上述类型的图表叫什么。我检查了点图,但它只能垂直堆叠。

最佳答案

此解决方案绘制由 x 分面的三个条形图集。每组中条形的高度由 value 除以 3 的余数确定。水平间距由自然几何间距提供。使用白色网格线创建垂直间距。

library(ggplot2)
library(reshape2)

数据

dataset <- data.frame('x' = 1:5, 'value' = c(10, 5, 7, 4, 12))

由于每个 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

现在,我们将熔化数据框以进行绘图:

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

情节

首先,我们将制作一个常规的条形图。我们可以使用 switch 参数将分面标签移动到绘图区域的底部。

plt <- ggplot(data = dataset)
plt <- plt + geom_col(aes(x=variable, y = magnitude), fill = 'black')
plt <- plt + facet_grid(.~x, switch="both")

然后我们将使用 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)

我们可以使用 geom_text() 添加 value 标签。我们将只使用 col2 记录中的 x 值,这样我们就不会在每个集合中的每个条上绘制值(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')

enter image description here

关于r - 如何在R中绘制下图?这些类型的图表叫什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53468090/

相关文章:

R Shiny dplyr 无功滤波器

R 重命名一个对象/data.frame 没有中间对象

r - 使用 lapply 和 !is.na 对 R 中的列表向量进行子集化

r - 通过回归截距对格子面板进行排序

r - ggplot 增加箱线图之间的距离

javascript - Flot饼图系列名称 "undefined"

android - 在 AChartEngine 中组合折线图和条形图

r - 在 R 中拟合 Log Pearson III 的问题

r - 增加 geom_line 图的标签间距

c++ - C/C++ 条形图