R 在ggplot2中刻面数据时,如何在比例上设置不同的打断和标签?
考虑以下代码:R 在ggplot2中刻面数据时,如何在比例上设置不同的打断和标签?,r,ggplot2,facet,R,Ggplot2,Facet,考虑以下代码: library(ggplot2) data = data.frame(x = c(1, 2, 3, 4, 5, 6), label = c("foo", "bar", "bar", "baz", "baz", "boo"),
library(ggplot2)
data = data.frame(x = c(1, 2,
3, 4,
5, 6),
label = c("foo", "bar",
"bar", "baz",
"baz", "boo"),
type = c(1, 1,
2, 2,
3, 3))
ggplot(data, aes(x = x, y = c(1))) +
labs(x = "", y = "") +
theme_bw() +
facet_wrap(~ type, ncol = 1, scales = "free_x") +
scale_x_discrete(aes(breaks = x, labels=label), limits = 1:6) +
geom_point()
它生成图像:
问题是忽略了我的scale\u x\u discrete()
。我希望每个方面的x比例在data$label
中显示标签,但仅在有数据的地方显示。换句话说,我想要这样的东西,但在一张图表上:
如何操作?将参数更改为
scales=“free”
。我修改了示例,添加了'y=type',而不是常数c(1),以获得不同的刻度
ggplot(data, aes(x = x, y = type)) +
labs(x = "", y = "") +
theme_bw() +
facet_wrap(~ type, ncol = 1, scales = "free") +
scale_x_discrete(aes(breaks = x), labels = data$label, limits = 1:6) +
geom_point()
使用scales=“free_y”
您可能需要单独构建绘图,然后使用
网格将它们合并。排列:
library(ggplot2)
data = data.frame(x = c(1, 2,
3, 4,
5, 6),
label = c("foo", "bar",
"bar", "baz",
"baz", "boo"),
type = c(1, 1,
2, 2,
3, 3))
library(gridExtra) # Using V 2.0.0
p = list()
for(i in 1:3) {
df = subset(data, type == i)
p[[i]] = ggplot(df, aes(x = x, y = c(1)) ) +
labs(x = "", y = "") +
theme_bw() +
expand_limits(x = c(1, 6)) +
facet_wrap(~ type, ncol = 1) +
scale_x_continuous(breaks = df$x, labels = df$label) +
geom_point()
}
grid.arrange(grobs = p, ncol = 1)
我认为您的代码中有一个输入错误,要生成您需要的图表:ggplot(数据,aes(x=x,y=c(1))
而不是ggplot(数据,aes(x=x,y=c(0)))
您是对的。我已经修复了代码,谢谢。@nongkrong不确定这是否与OP考虑的问题更接近。您可能可以使用面板变量use@mpalanco谢谢你的回答,但这对我不起作用。我要找的是你的第一张图表,但是每个方面的轴断裂都不同。第一个应该只有foo和bar,第二个bar和baz,第三个baz和boo。y
也应该是常量。我想展示的是时间的变化。每个类型
表示一个时间:t1、t2和t3,数据位置随时间变化。您可以看到,bar
从t1的2变为t2的3,而baz
从t2的3变为t3的4。这就是为什么每一个面上的断裂都是不同的。@VítorBaptista在最后一个图中,通过观察y轴,你可以看到时间的变化。例如,条从t1中的1变为t2中的2。@mpalanco我明白了。。。尽管如此,我认为将时间保持在x轴上要容易得多。不确定ggplot中的单个图表是否可行,thoughHi Sandy,你能保持所有x标度的限制相同吗?我试图修改您的代码,但无法完成。我已更改了绘图和代码。这次我明白了吗?是的,我最后也是这么做的。似乎没有办法用一个单一的情节来做我们想要做的事情。我接受你的回答。谢谢你的帮助!
ggplot(data, aes(x = label, y = type)) +
labs(x = "", y = "") +
theme_bw() +
facet_wrap(~ type, ncol = 1, scales = "free") +
geom_point()
library(ggplot2)
data = data.frame(x = c(1, 2,
3, 4,
5, 6),
label = c("foo", "bar",
"bar", "baz",
"baz", "boo"),
type = c(1, 1,
2, 2,
3, 3))
library(gridExtra) # Using V 2.0.0
p = list()
for(i in 1:3) {
df = subset(data, type == i)
p[[i]] = ggplot(df, aes(x = x, y = c(1)) ) +
labs(x = "", y = "") +
theme_bw() +
expand_limits(x = c(1, 6)) +
facet_wrap(~ type, ncol = 1) +
scale_x_continuous(breaks = df$x, labels = df$label) +
geom_point()
}
grid.arrange(grobs = p, ncol = 1)