This happened to me all the time. The trick is knowing that aes()
maps data to aesthetics. If there's no data to map (e.g., if you have a single value that you determine), there's no reason to use aes()
. I believe that only things inside of an aes()
will show up in your legend.
Furthermore, when you specify mappings inside of ggplot(aes())
, those mappings apply to every subsequent layer. That's good for your x and y, since both geom_point
and geom_text
use them. That's bad for size = count
, as that only applies to the points.
So these are my two rules to prevent this kind of thing:
- Only put data-based mappings inside of
aes()
. If the argument is taking a single pre-determined value, pass it to the layer outside of aes()
.
- Map data only for those layers that will use it. Corollary: only map data inside of
ggplot(aes())
if you're confident that every subsequent layer will use it. Otherwise, map it at the layer level.
So I would plot this thusly:
p <- ggplot(data = df, aes(x = x, y = y)) + geom_point(aes(size = count))
p + geom_text(aes(label = label), size = 4, vjust = 2)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…