我试图绘制一条线图,该线图在x
中具有两个x-axis
变量,在y
中具有一个连续的y-axis
变量。 x1
和x2
的计数不同。 df
如下所示-
df <- structure(list(val = c(3817,2428,6160,6729,7151,7451,6272,7146,7063,6344,5465,6169,7315,6888,7167,6759,4903,6461,7010,7018,6920,3644,6541,31862,31186,28090,28488,29349,28284,25815,23529,20097,19945,22118), type = c("1wt", "1wt", "3wt", "3wt", "3wt", "5wt", "5wt", "7wt", "7wt", "7wt","10wt","10wt","10wt","15wt","15wt","20wt","20wt","25wt","25wt","25wt","30wt","30wt","30wt","20m","20m","15m","15m","15m","10m","10m","5m", "5m", "5m", "5m"), group = c("A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B")), row.names = c(NA, 34L), class = "data.frame")
其中x
变量是-
x1 <- factor(df$type, levels = c("1wt", "3wt", "5wt", "7wt", "10wt", "15wt", "20wt", "25wt", "30wt"))
和
x2 <- factor(df$type, levels = c("20m", "15m","10m","5m"))
我想分别为x1
和x2
用不同的颜色和图例的行,如x轴上的df$group
和y处的df$val
-轴。你能帮我做这个吗?预先感谢。
答案 0 :(得分:0)
编辑:添加在下面
这是一种假设方法是将A组中可能的类型值的范围与B组中可能的值的范围进行映射。
可以手动添加标签,但是我认为没有一种简单的方法可以在一个图中同时使用两个分类x轴。
df2 <- df %>%
mutate(x = case_when(type == "1wt" ~ 0,
type == "3wt" ~ 1,
type == "5wt" ~ 2,
type == "7wt" ~ 3,
type == "10wt" ~ 4,
type == "15wt" ~ 5,
type == "20wt" ~ 6,
type == "25wt" ~ 7,
type == "30wt" ~ 8,
type == "20m" ~ 0/3 * 8,
type == "15m" ~ 1/3 * 8,
type == "10m" ~ 2/3 * 8,
type == "5m" ~ 3/3 * 8))
ggplot(df2, aes(x, val, color = group, group = group)) +
geom_point() +
geom_smooth(method = lm)
第二种方法
听起来OP希望以某种方式在数字上使用type
值。如果它们不是按照所描述的方式在本质上相互链接,那么我怀疑将它们像绘制一样会产生误导。 (请参阅here,以了解为什么会造成麻烦。)
也就是说,这就是您的操作方法。首先,这是一种仅使用type
的数字部分的方法。请注意,与B组相关联的“ m”在底部,而“ wt”在顶部与组A关联,如以下OP注释中添加的示例所示。我已经在轴上添加了颜色以阐明这一点。视觉上有点违反直觉,因为与上轴相关的点在底部,反之亦然。
df2 <- df %>%
# First, let's take the number used in "type" without adjustment
mutate(x_unadj = parse_number(type))
ggplot(df2, aes(x_unadj, val, color = group, group = group)) +
geom_point() +
geom_smooth(method = lm) + # Feel free to use other smoothing method, but
# not obvious to me what would be improvement.
scale_x_continuous("m", sec.axis = sec_axis(~., name = "wt")) +
theme(axis.text.x.bottom = element_text(color = "#00BFC4"),
axis.title.x.bottom = element_text(color = "#00BFC4"),
axis.text.x.top = element_text(color = "#F8766D"),
axis.title.x.top = element_text(color = "#F8766D"))
如果不能令人满意,我们可以使用
反转两个轴的顺序scale_x_reverse("m", sec.axis = sec_axis(~., name = "wt")) +
使用ggplot 3.1.0(自2018年10月起),我无法使辅助x轴沿与主轴相反的方向移动。 2017年的This example似乎不再适用于此版本。截至2018年12月,proposed fix正在接受审核,旨在解决此问题。