如何使用2个变量创建ggplot?

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

How to create ggplot with 2 variables?

问题

我的数据看起来是这样的:

```R
df <- structure(list(`记录ID` = c(6L, 7L, 9L, 11L, 12L, 13L, 14L, 
16L, 17L, 18L), 初始值 = c(2L, 0L, 0L, 2L, 22L, 4L, 0L, 9L, 
16L, 20L), 最终值 = c(2L, 2L, 2L, 0L, 19L, 0L, 0L, 4L, 4L, 20L
)), class = "data.frame", row.names = c(NA, -10L))

我正在尝试制作一个类似于如何使用2个变量创建ggplot?的图表

唯一的区别是图表中的“城市”将来自于我的数据中的“记录ID”。我一直很困扰,如果有人能帮我,非常感谢!

我尝试过许多方法,但都没有帮助。


<details>
<summary>英文:</summary>

My data looks like this:

df <- structure(list(Recorded ID = c(6L, 7L, 9L, 11L, 12L, 13L, 14L,
16L, 17L, 18L), Initial = c(2L, 0L, 0L, 2L, 22L, 4L, 0L, 9L,
16L, 20L), Final = c(2L, 2L, 2L, 0L, 19L, 0L, 0L, 4L, 4L, 20L
)), class = "data.frame", row.names = c(NA, -10L))

 I am trying to make a plot that is similar to ![this](https://i.stack.imgur.com/u5IeV.png)

EXCEPT only change would be is that City on that plot would be &quot;Record ID&quot; from my data. I am having a lot of trouble if someone could help me thank you so much!

I have tried many things but none have helped

</details>


# 答案1
**得分**: 1

这是一个可以使用`geom_bar`完成的“条形图”:

```R
df %>%
  pivot_longer(-`Recorded ID`, names_to = 'Key') %>%
  mutate(Recorded.ID = factor(`Recorded ID`)) %>%
  ggplot(aes(y = Recorded.ID, x = value, fill = Key)) + 
  geom_bar(stat = 'identity', position = 'dodge')

如何使用2个变量创建ggplot?

英文:

This is a bar plot which can be accomplished using geom_bar:

df %&gt;%
  pivot_longer(-`Recorded ID`, names_to = &#39;Key&#39;)%&gt;%
  mutate(Recorded.ID = factor(`Recorded ID`))%&gt;%
  ggplot(aes(y = Recorded.ID, x = value, fill = Key) ) + 
  geom_bar(stat = &#39;identity&#39;, position = &#39;dodge&#39;)

如何使用2个变量创建ggplot?

huangapple
  • 本文由 发表于 2023年7月17日 09:19:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76701020.html
匿名

发表评论

匿名网友

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

确定