以另一列标记 x 轴,并根据条件标记图表中的字符串。

huangapple go评论62阅读模式
英文:

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 轴,并根据条件标记图表中的字符串。

我想要绘制x轴是City,y轴是popu的图表,

但是x轴标签不是按City,颜色按Country分组,
就像这样,相同的Country会有相同的颜色并且彼此相邻:
以另一列标记 x 轴,并根据条件标记图表中的字符串。

还希望当pop > 7500时标记City,例如像这样:
以另一列标记 x 轴,并根据条件标记图表中的字符串。

有人能帮忙吗?

英文:

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 &lt;- data.frame(City = LETTERS[1:9],
           popu = c(8975,3421,5433,1066,4529,9012,6732,5801,3396),
           Country = c(&quot;UA&quot;,&quot;UA&quot;,&quot;AS&quot;,&quot;UK&quot;,&quot;UA&quot;,&quot;AS&quot;,&quot;UK&quot;,&quot;Is&quot;,&quot;Is&quot;))

My current code looks like this:

d %&gt;% 
  ggplot(aes(City, popu)) +
  geom_point(aes(color=Country))

Which gives me :
以另一列标记 x 轴,并根据条件标记图表中的字符串。

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:
以另一列标记 x 轴,并根据条件标记图表中的字符串。

also label City if pop > 7500, for example like :
以另一列标记 x 轴,并根据条件标记图表中的字符串。

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>



huangapple
  • 本文由 发表于 2023年6月26日 11:04:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76553291.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定