在geom_tile中的特定区域周围绘制线 [英] draw lines around specific areas in geom_tile
问题描述
我有以下数据框(df1)
,它从中生成了geom_tile
图.
I have the following data frame (df1)
which i generated a geom_tile
plot from it.
X Y Z
1 1 0.343
5 4 0.134
10 6 0.564
20 8 0.532
40 9 0.235
46 12 0.425
,我还有另一个数据框,我想用它来画线(df2)
:
and i have another data frame which i want to use to draw the lines (df2)
:
a b c d
1 1 0.05 good
5 4 0.01 better
10 6 0.03 middle
20 8 0.1 bad
40 9 0.2 bad
46 12 0.22 bad
因此,想法是a
和X
相同,并且b
和Y
是相同的值.
so the idea, is that a
and X
are the same and b
and Y
are the same values.
我要做的是根据df2
中d
的值在geom_tile
区域周围绘制一些线.因此在每个不同的区域都会有不同的色线,例如(好是红色,更好是蓝色,...)
what i want to do is to draw some lines around the geom_tile
areas depending on the value of d
in df2
. so in each different area there will be a different color line e.g (good is red, better is blue, ...)
我尝试使用geom_contour
,但问题是它以非常难看的方式绘制线条,并且我无法以一种很好的方式指定坐标..
i tried to use geom_contour
but the problem it draws lines in a very ugly way and i wasn't able to specify coordinates in a good way ..
注意
Note
- 某些区域可能不是直线的
- 数据帧更大,这是一个测试数据,可以解释这个想法
推荐答案
我建议首先将两个数据框合并在一起,因为它们在两列中具有相同的值.
I would suggest, first, to merge both data frame together as they have the same values in two columns.
df.new<-merge(df1,df2,by.x=c("X","Y"),by.y=c("a","b"))
df.new
X Y Z c d
1 1 1 0.343 0.05 good
2 10 6 0.564 0.03 middle
3 20 8 0.532 0.10 bad
4 40 9 0.235 0.20 bad
5 46 12 0.425 0.22 bad
6 5 4 0.134 0.01 better
然后在aes()
中为Z(如果需要)和color=d
设置fill=
. geom_tile()
中的size=2
将确保瓷砖周围的线条更清晰可见.
Then in aes()
set fill=
for the Z (if necessary) and color=d
. size=2
in geom_tile()
will ensure that lines around tiles are better visible.
ggplot(df.new,aes(X,Y,fill=Z,color=d))+geom_tile(size=2)
也可以在不合并数据帧的情况下获得类似的结果-您应该使用两个geom_tile()
调用(每个数据帧一个),然后在第二个geom_tile()
(已设置颜色)中在aes()
之外添加fill=NA
.
Similar results can be achieved also without merging data frame - you should use two geom_tile()
calls (one for each data frame) and in second geom_tile()
(where color is set) add fill=NA
outside aes()
.
ggplot()+geom_tile(data=df1,aes(X,Y,fill=Z))+
geom_tile(data=df2,aes(a,b,color=d),size=2,fill=NA)
这篇关于在geom_tile中的特定区域周围绘制线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!