Reputation: 17
I have such data table structure, and I am so struggle how could I plot two line to clearly indicate two condition:
> Dependent Counts Indication
> 0 2 Stay
> 1 4 Stay
> 2 1 Stay
> 0 11 Left
> 1 5 Left
> 2 3 Left
> 3 2 Left
> 4 1 Left
[Btw] I saw some reference/ question asked and solution provided Dual line on single plot could definitely achievable by:
x <- c(...)
y1 <- c(...)
y2 <- c(...)
But this kind of solution did not hit my needs. I am seeking another way to do this as my table is prepared in the above-mentioned form.
Upvotes: 0
Views: 81
Reputation: 17
Finally I worked out the exact answer I am looking for.
ggplot() + geom_line(aes(subset(dataStay_Left$Dependents,
dataStay_Left$ind=="Stay"), subset(dataStay_Left$Counts,
dataStay_Left$ind=="Stay"), group=1)) +
geom_line(aes(subset(dataStay_Left$Dependents, dataStay_Left$ind=="Left"),
subset(dataStay_Left$Counts, dataStay_Left$ind=="Left"), group=2))
Thanks for the help provided and the discussion.
Upvotes: 0
Reputation: 23101
with ggplot
library(ggplot2)
ggplot(df, aes(x=Dependent, y=Counts, group=Indication, color=Indication)) + geom_line()
Upvotes: 0
Reputation: 6516
if df
is your dataframe:
df <- data.frame("Dependent"=c(0,1,2,0,1,2,3,4),
"Counts"=c(2,4,1,11,5,3,2,1),
"Indication"=c("Stay","Stay","Stay","Left","Left","Left","Left","Left"))
library(tidyr)
df_tidy <- spread(df, Indication, Counts)
plot(df_tidy$Dependent, df_tidy$Left, type="l")
lines(df_tidy$Dependent, df_tidy$Stay, col="red")
I am first using tidyr
to "spread" your dataframe and from there you can use the standard plot function.
Spread:
This function takes data that is in a key-value format and returns a rectangular tidy cell format. As you can see spread() restructures the dataframe by removing redundant rows without losing any information.
For more information on spread
and tidyr
, please look here.
Upvotes: 1