英文:
label x-axis by another column and label string at plot based on condition
问题
我想要在ggplot中绘制geom_point的图表。x轴是City
,y轴是popu
。
我有这样的数据框:
d <- data.frame(City = LETTERS[1:9],
popu = c(8975,3421,5433,1066,4529,9012,6732,5801,3396),
Country = c("UA","UA","AS","UK","UA","AS","UK","Is","Is"))
我的当前代码如下:
d %>%
ggplot(aes(City, popu)) +
geom_point(aes(color=Country))
我想要绘制x轴是City
,y轴是popu
的图表,
但是x轴标签不是按City,颜色按Country
分组,
就像这样,相同的Country会有相同的颜色并且彼此相邻:
有人能帮忙吗?
英文:
I want to get graphy of geom_point in ggplot. x-axis is City
and y is popu
I have this data frame like :
d <- data.frame(City = LETTERS[1:9],
popu = c(8975,3421,5433,1066,4529,9012,6732,5801,3396),
Country = c("UA","UA","AS","UK","UA","AS","UK","Is","Is"))
My current code looks like this:
d %>%
ggplot(aes(City, popu)) +
geom_point(aes(color=Country))
I would like to get plot with x-axis is City
and y is popu
,
but x-axis label not by City and color by Country
,
kind of like this,same Country will get same color and nearby:
also label City if pop > 7500, for example like :
Can anybody help?
答案1
得分: 1
这是我对你想要的最佳猜测:
```R
library(ggplot2)
library(dplyr)
ggplot(d, aes(x = Country, y = popu)) +
geom_point(
aes(color = Country),
position = position_jitter(width = 0.5, seed = 1)
) +
geom_text( # 标记人口超过7500的城市
aes(label = ifelse(popu > 7500, paste("City", City), "")),
position = position_jitter(width = 0.5, seed = 1),
vjust = 1.2
)
使用 position = position_jitter
将防止点重叠,设置种子将确保文本标签以相同的方式抖动。
[![在此输入图片描述][1]][1]
[1]: https://i.stack.imgur.com/h4dE8.png
<details>
<summary>英文:</summary>
This is my best guess as to what you want:
library(ggplot2)
library(dplyr)
ggplot(d, aes(x = Country, y = popu)) +
geom_point(
aes(color = Country),
position = position_jitter(width = 0.5, seed = 1)
) +
geom_text( # label cities over 7500 population
aes(label = ifelse(popu > 7500, paste("City", City), "")),
position = position_jitter(width = 0.5, seed = 1),
vjust = 1.2
)
Using `position = position_jitter` will keep the points from overlapping, and setting the seed will make sure the text labels get jittered the same way.
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/h4dE8.png
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论