我要创建一个非常简单的发散条形图:左侧应为APD2,右侧应为APD1。因此,对于每个x值,应绘制相应的y值。但这就是我努力的重点。我猜这是行不通的,因为y轴范围设置不正确。此外,这可能与以下事实有关:我不知道如何设置中断和标签。 APD1和APD2的y值永远不会超过7000。中断是否应该从0或-7000开始?
这是当前情节:
这是我理解的代码:
library(ggplot2)
library(ggthemes)
ggplot(df, aes(x = depth, y = "Number of photons", fill = APD)) + # Fill column
geom_bar(stat = "identity", width = .6) +
scale_y_continuous(breaks = c(-7000, -6000, -5000, -4000, -3000, -2000, -1000, 0, 1000, 2000, 3000, 4000, 5000, 6000, 7000),
labels = c(7000, 6000, 5000, 4000, 3000, 2000, 1000, 0, 1000, 2000, 3000, 4000, 5000, 6000, 7000)
) +
coord_flip() +
labs(title="APD ratio") +
theme_tufte() +
theme(plot.title = element_text(hjust = .5),
axis.ticks = element_blank()) +
scale_fill_brewer(palette = "Dark2")
这里的数据:
depth= c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
APD_first= c(5900, 5918, 6166, 6167, 5947, 5668, 5633, 5716, 5533, 5463, 5428, 5415, 5326, 5346, 5695, 5771, 5748)
df1<- data.frame(depth, APD_first)
df1["APD"]<- "APD1"
colnames(df1)[2]<- "Number of photons"
depth= c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
APD_second= c(5616, 5710, 5843, 5767, 5766, 5541, 5467, 5406, 5396, 5307, 5229, 5255, 5156, 5359, 5383, 5710, 5651)
df2<- data.frame(depth, APD_second)
df2["APD"]<- "APD2"
colnames(df2)[2]<- "Number of photons"
df<- rbind(df1, df2)
答案 0 :(得分:1)
您是否正在寻找类似的东西?
colnames(df)[2] <- "Number.of.photons"
ggplot(df,
aes(x = depth, y = ifelse(APD == "APD1", Number.of.photons, -Number.of.photons),
fill = APD)) +
geom_col() +
scale_y_continuous(breaks = seq(-7000, 7000, 1000),
labels = abs) +
scale_fill_brewer(palette = "Dark2") +
coord_flip()
如果您绝对需要在ggplot的美学映射中引用名称中带有空格的列,请使用反引号:即`Number of photons`
而不是“光子数”。后者将产生您所看到的结果,因为它被解释为值1的字符串,而不是列名。不过,一般来说,如果将空格替换为“。”,则麻烦会减少,因为这使您可以以无引号的形式引用列名。