I have some count variables against which I want to make bar-plots on the same y-axis but I have no grouping variable. Something like the following plot
B <- 25
iter_M1
[1] 5 13 14 11 7 8 10 14 10 5 7 13 10 12 4 5 9 6 5 12 8 8 7 11 9
max_M1 <- max(iter_M1)
count_M1 <- integer(max_M1)
for(i in 1:max_M1)
{
for(j in 1:B)
{
if(iter_M1[j] == i)
count_M1[i] = count_M1[i] +1
}
}
count_M1
[1] 0 0 0 1 4 1 3 3 2 3 2 2 2 2
df <- data.frame(x = 1:max_M1, y = count_M1)
p_M1 <-ggplot(data=df, aes(x=x, y=y)) + geom_bar(stat="identity")
p_M1
This results in a plot like this
and another similar variable
iter_M2
[1] 3 1 3 2 6 3 4 4 3 7 4 2 2 3 4 3 4 4 1 3 7 3 2 4 2
max_M2 <- max( iter_M2)
count_M2 <- integer(max_M2)
for(i in 1:max_M2)
{
for(j in 1:B)
{
if(iter_M2[j] == i)
count_M2[i] = count_M2[i] +1
}
}
count_M2
[1] 2 5 8 7 0 1 2 df1 <- data.frame(x1 = 1:max_M2, y1 = count_M2)
p_M2 <-ggplot(data=df1, aes(x=x1, y=y1)) +
geom_bar(stat="identity") p_M2
which results in a second plot as
and similar variables like these... How can I plot this data side by side. Also the way I'hv generated data currently, there is no common y-axis for all x-axis. Are there some suggestion to generate such a plot or dataset in other format to achive the requried plot.
As suggested in the comments, making a factor (class) is the easiest way, allowing you to facet the plot.
But you seem explicitly just to want to have the same y-axis. This is achievable with the scale limits. For example, generate a vector with the limits based on max
and then use this in your plots.
ylimits <- c(0, max(c(count_M1, count_M2)))
p_M1 + ylim(ylimits)
p_M2 + ylim(ylimits)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.