我想用X值作为测量的子集,Y值作为测量数据的另一个子集来绘制一个图.

在下面的例子中,我有4个产品p1、p2、p3和p4.每一种都是根据它们的歪斜、 colored颜色 和版本定价的.

我的以下try 失败了,错误如下:

错误:美学长度必须为1,或与长度相同

library(ggplot2)
product=c("p1","p1","p1","p1","p1","p1","p1","p1","p2","p2","p2","p2","p2","p2","p2","p2","p3","p3","p3","p3","p3","p3","p3","p3","p4","p4","p4","p4","p4","p4","p4","p4")
skew=c("b","b","b","b","a","a","a","a","b","b","b","b","a","a","a","a","b","b","b","b","a","a","a","a","b","b","b","b","a","a","a","a")
version=c(0.1,0.1,0.2,0.2,0.1,0.1,0.2,0.2,0.1,0.1,0.2,0.2,0.1,0.1,0.2,0.2,0.1,0.1,0.2,0.2,0.1,0.1,0.2,0.2,0.1,0.1,0.2,0.2,0.1,0.1,0.2,0.2)
color=c("C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2","C1","C2")
price=c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32)
df = data.frame(product, skew, version, color, price)
# First plot all the data
p1 <- ggplot(df, aes(x=price, y=price, colour=factor(skew))) + geom_point(size=2, shape=19)
p1 <- p1 + facet_grid(version ~ color)
p1 # This gavea very good plot. So far so good
# Now plot P3 vs P1
p1 <- ggplot(df, aes(x=subset(price, product=='p1'), y=subset(price, product=='p3'), colour=factor(skew))) + geom_point(size=2, shape=19)
p1
# failed with: Error: Aesthetics must either be length one, or the same length as the dataProblems:subset(price, product == "p1"), subset(price, product == "p3")

这是我期待的结果:

这是我期待的结果

推荐答案

问题是skew没有被细分到colour=factor(skew)中,所以它的长度是错误的.由于subset(skew, product == 'p1')subset(skew, product == 'p3')相同,因此在本例中,使用哪个子集并不重要.因此,您可以通过以下方式解决问题:

p1 <- ggplot(df, aes(x=subset(price, product=='p1'),
                     y=subset(price, product=='p3'),
                     colour=factor(subset(skew, product == 'p1')))) +
              geom_point(size=2, shape=19)

请注意,大多数R用户会将其写得更简洁:

p1 <- ggplot(df, aes(x=price[product=='p1'],
                     y=price[product=='p3'],
                     colour=factor(skew[product == 'p1']))) +
              geom_point(size=2, shape=19)

R相关问答推荐

Row_wise 和 column_wise 使用 fill 和 down/across 填充 NA

在 tibble R 的截止范围内随机采样

R markdown beamer 演示返回未定义的控制序列

R ggplot2 堆叠列而不是分组

根据对 R 中的特定列求和创建一个新值

R 当前时间(以毫秒为单位)

如何求和每个月和年的值总数并通过 R 中的其他列加入

如果行值高于某个阈值,则返回列标题

在R中按组查找最长的值序列

R Plotly Bar Chart - 添加水平线标记

取R中数组中所有元素的矩阵乘积?

如何使用“ggplot2”从数字矩阵中绘制栅格

将随机观察值的总和计算为 R 中每周的总和

如何将所有列重命名为R中的中间分隔符?

在 qqnorm 图中添加一条直线

忽略列zoom 行值

如何将行添加到 R Shiny 表

将数据框列表合并为一个数据框并一步汇总

如何在 R 中设置错误消息的宽度?

R:如何在一个图上绘制多个图(shiny )