r - using ggplot to show a dot as the value [closed]

人盡茶涼 提交于 2021-02-08 12:14:29

问题


I have a data frame like this:

CWSR = c(0.2, 0.1, 0.5, 0.6, 0.4, 0.8, 0.9, 0.7, 0.1, 0.2) 
BPA = c(1,5,9,8,4,3,2,1,4,3) 
df = data.frame(CWSR, BPA)

   CWSR BPA
1   0.2   1
2   0.1   1
3   0.5   9
4   0.1   2
5   0.4   4
6   0.1   2
7   0.9   2
8   0.1   3
9   0.1   2
10  0.2   3

I have generated the below histogram but instead of the layout produced, I want to display show a dot for each value in my graph, rather than an entire bar. Currently I am using this:

p <- ggplot(HData, aes(BPA, CWSR))
p + geom_bar(stat="identity")

enter image description here

In addition, I am looking to count the number of instances of BPA IF the value of CWSR is equal to 0.1, then to display this as a percentage.

So in the example above, for BPA value of 1, this occurs once for the value of CWSR 0.1 (line 2) so this would show 100%. For the BPA value of 2, this occurs 3 times for the value of CWSR 0.1 (lines 4,6,9) BUT there is a BPA value of 2 and CWSR value not equal to 1 (line 7, 0.9) so the total percentage would show as 75% (3 out of 4).

I have tried something like this:

df %>%
  group_by(BPA) %>% 
  summarise(num = n(),
            totalCWSR = sum(CWSR==1), totalP = (totalCWSR / num * 100)) 

But not sure if it is correct or how to display in ggplot?

I hope this is clearer, apologies for not providing as much detail previously.


回答1:


I'm not sure this is what you want, and there is probably a much more elegant way of doing this, but here you have one possible solution that aggregates your values in CWSR given the BPA values, and then does a simple geom_point plot:

library(dplyr)
library(ggplot2)

CWSR = c(0.2, 0.1, 0.5, 0.6, 0.4, 0.8, 0.9, 0.7, 0.1, 0.2) 
BPA = c(1,5,9,8,4,3,2,1,4,3) 
df = data.frame(CWSR, BPA)

df %>% group_by(BPA) %>%
  summarise(CWSRsum = sum(CWSR)) %>%
  arrange(BPA) %>%
  ggplot(aes(BPA, CWSRsum)) + geom_point(size=5)




回答2:


If for your plot you are looking for a 'lollipop plot' where the dot is placed on the end of a simple line instead of the whole bar, there are many ways to achieve it. Below is a minor modification to @Oriol's code example with a line segment added, though to be effective such plots are normally ordered from the largest to the smallest value:

df %>% 
  group_by(BPA) %>%
  summarise(CWSRsum = sum(CWSR)) %>%
  arrange(BPA) %>%
  ggplot(aes(BPA, CWSRsum)) + 
  geom_segment(aes(xend = BPA, y = 0, yend = CWSRsum), colour = "gray40", linetype = 3)+
  geom_point(size=4, colour = "gray60") +
  theme_bw()+
  theme(panel.grid = element_blank())



来源:https://stackoverflow.com/questions/48039079/r-using-ggplot-to-show-a-dot-as-the-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!