Reputation: 3
I'm trying to graph the number of times a price appears in my database group by chain, represent the chain with different colours and draw a line that connect the x axis (y=0) to the maximum point at each price (x value) with the chain colour. If two different chains have the same price I want the lines to overlap. This is my data: Data
For example: price 39.5 appears two times for chain b, and one for chain a.
I want a graph with points and lines. Each point must be the number of times a price appears in each chain coloured according to chain. Up to this point I can graph it, I get this graph:
The problem arises when I try to connect points with x axis, I try geom_segment but it gives me a weird graph with diagonal lines when the same price appears in more than one chain, like this:
This is my code:
gP1 <- ggplot(fP1, aes(Price, N, color=Chain), group=Price) +
geom_point() +
geom_segment(aes(xend=N, color=Chain, group=Price), yend=0)
Any help would be appreciated, I want to get a graph like this one:
Thanks in advance!
Upvotes: 0
Views: 1605
Reputation: 39603
Try this approach with geom_segment()
defining the proper values for x and y positions. Here the code:
library(ggplot2)
#Data
fP1 <- data.frame(Price=c(39.5,39.5,39.9,39.9,40,42.5,42.8,45,46,47.9,50),
Chain=c('a','b','h','c','d','e','f','f','e','f','g'),
N=c(1,2,1,4,1,1,1,1,2,1,3))
#Plot
ggplot(fP1, aes(Price, N, color=Chain, group=Price)) +
geom_point() +
geom_segment( aes(x=Price, xend=Price, y=0, yend=N))+
theme_bw()
Output:
The previous sketch considers all the setting for geom_segment()
. It can by simplified to this (Many thanks and all credit to @RuiBarradas):
#Plot 2
ggplot(fP1, aes(Price, N, color=Chain, group=Price)) +
geom_point() +
geom_segment( aes(xend=Price,yend=0))+
theme_bw()
It will produce same output.
Upvotes: 4