ggplot2 line plot order
geom_path()
will join points in the original order, so you can order your data in the way you want it joined, and then just do + geom_path()
. Here's some dummy data:
dat <- data.frame(x = sample(1:10), y = sample(1:10), order = sample(1:10))
ggplot(dat[order(dat$order),], aes(x, y)) + geom_point() + geom_text(aes(y = y + 0.25,label = order)) +
geom_path()
How can I define line plotting order in ggplot2 for grouped lines?
One way would be to subset your data when you draw lines. You want to draw lines for the false group first, then the true group.
ggplot(data = df, aes(x = x, y = y, colour = flag,
group = group)) +
geom_line(data = subset(df, flag == "false"), size = 3) +
geom_line(data = subset(df, flag == "true"), size = 3)
Arrange line plot by order of the variables in data frame
Use geom_path
, this will sort by occurrence in your data frame.
I'd advise keep dates actually stored as dates. The problem is that your factor/character order is defined by the day. By converting this into dates, and converting this into a character with as.character(lubridate::dmy(day))
, the order will be "correct".
# devtools::install_github("alistaire47/read.so")
library(tidyverse)
library(lubridate)
#>
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#>
#> date, intersect, setdiff, union
dataset_lago <- read.so::read_md("| Depth | P_Total | day |
| -------- | -------------- | -------------- |
| 0 | 401.27 | 26_05_11 |
| 2 | 206.24 | 26_05_11 |
| 4.8 | 163.79 | 26_05_11 |
| 0 | 255.92 | 12_01_12 |
| 2 | 167.72 | 12_01_12|
| 5 | 300.29 | 12_01_12 | ")
dataset_lago %>%
mutate(day = dmy(day)) %>%
ggplot(mapping= aes(x = P_Total, y= Depth))+
geom_path(aes(P_Total, colour= as.character(day)))+
scale_y_reverse()+
theme(plot.title = element_text(hjust = 0.5))+
labs(x = "P_Total", y = "Depth") +
theme_minimal()
Created on 2021-01-23 by the reprex package (v0.3.0)
ggplot geom_line: Change order of plotting
I found the solution in the process of writing the question, and I thought I might share this, since it could be helpfull for other people :°).
It seems like we can refactor the leves according to a different column like this:
df$ID <- as.factor(df$ID)
df$System <- as.factor(df$System)
df$ID <- factor(df$ID,
levels = c(c(unique(as.factor(df$ID[c(which(df$System == 'a'))]))),
c(unique(as.factor(df$ID[c(which(df$System == 'b'))]))),
c(unique(as.factor(df$ID[c(which(df$System == 'c'))]))),
c(unique(as.factor(df$ID[c(which(df$System == 'd'))])))
)
)
Executing this, we're looking for those row'swhich
are part of group a
. Then we take the line number to get the ID's of those samples and pass them as an unique (there are multiple samples with the same name) vector to the levels
parameter. We repeat that for each group.
This results in this plot (take the code from the question):
Now the lines in the largest group a are plotted first
Change the overlaying order of lines in ggplot
So actually the last level of col
is on the top. So you need to change the order of the factor and reverse the colors as red is automatically mapped to the first level (used standard colors to illustrate the problem):
pl_data$col <- factor(pl_data$col, c("r", "g", "b"))
ggplot(pl_data, aes(x = x, y = y, color = col)) +
geom_line(size = 3) +
scale_color_manual(values = c(r = "blue", g = "green", b = "red"))
## with standard colors of ggplot2, function taken from:
## http://stackoverflow.com/questions/8197559/emulate-ggplot2-default-color-palette
ggplotColours <- function(n = 6, h = c(0, 360) + 15) {
if ((diff(h) %% 360) < 1) h[2] <- h[2] - 360/n
hcl(h = (seq(h[1], h[2], length = n)), c = 100, l = 65)
}
pal <- setNames(ggplotColours(3), c("b", "g", "r"))
ggplot(pl_data, aes(x = x, y = y, color = col)) +
geom_line(size = 3) +
scale_color_manual(values = pal, breaks = c("b", "g", "r"))
ggplot - line ordering, one line on top of the other
Change the factor level order. Don't forget to change the group too.
See this related thread, why I used scales::hue()
etc
library(tidyverse)
forecast <- c(2,2,1,2,2,3,2,3,3,3,3)
actual <- c(2,2,1,2,2,3,2,3,2,2,1)
my_df <- data.frame(forecast = forecast, actual = actual, seq_order = 1:11)
my_df <-gather(my_df, line_type, value, -seq_order) %>% mutate(type = factor(line_type, levels = c('forecast','actual')))
ggplot(data=my_df, aes(x=seq_order, y = value,
colour = type, group = type)) +
geom_line()+
theme(legend.position="bottom") +
scale_color_manual(values = rev(scales::hue_pal()(2)))
Created on 2020-03-24 by the reprex package (v0.3.0)
Method of ordering groups in ggplot line plot
The issue is that the order by which geom_line
connects the points is determined by the value on the x-axis. To solve this issue simply swap x
and y
and make use of coord_flip
.
As no sample dataset was provided I use an example dataset based on mtcars
to illustrate the issue and the solution. In my example data make
is your vars
, value
your EI1
and name
your groups
:
library(ggplot2)
library(dplyr)
library(tidyr)
library(forcats)
example_data <- mtcars %>%
mutate(make = row.names(.)) %>%
select(make, hp, mpg) %>%
mutate(make = fct_reorder(make, hp)) %>%
pivot_longer(-make)
Mapping make
on x
and value
on y
results in an unordered line plot as in you example. The reason is that the order by which the points get connected is determined by value
:
example_data %>%
ggplot(aes(x = value, y = make, color = name, group = name)) +
geom_line() +
geom_point() +
xlab("EI1 (Expected Influence with Neighbor)") +
ylab("Variables")
In contrast, swapping x
and y
, i.e. mapping make
on x
and value
on y
, and making use of coord_flip
gives a nice ordererd line plot as the order by which the points get connected is now determined by make
(of course we also have to swap xlab
and ylab
):
example_data %>%
ggplot(aes(x = make, y = value, color = name, group = name)) +
geom_line() +
geom_point() +
coord_flip() +
ylab("EI1 (Expected Influence with Neighbor)") +
xlab("Variables")
Make a ggplot line plot where lines follow row order
Using your data,
ggplot(DF, aes(x=X,y=Y))+geom_point()+geom_path()
Produces this, which sounds like what you are asking(??)
Related Topics
How to Efficiently Read the First Character from Each Line of a Text File
Draw Multiple Squares with Ggplot
Ggplot Geom_Bar: Stack and Center
R Crashing While Displaying Ggplot After Update (Process Memory Read Out of Range)
R Leaflet - Use Date or Character Legend Labels with Colornumeric() Palette
Findassocs for Multiple Terms in R
Ggplot Set Scale_Color_Gradientn Manually
Axis Labels for Each Bar and Each Group in Bar Charts with Dodged Groups
Error While Using Install_Github | Devtools | Timeout Issue
Change a Column from Birth Date to Age in R
R: Replacing Foreign Characters in a String
Ggplot2: Plotting Order of Factors Within a Geom
Package 'Pbkrtest' Is Not Available (For R Version 3.2.2)
Margin Adjustments When Using Ggplot's Geom_Tile()
R - How to Use Selectinput in Shiny to Change the X and Fill Variables in a Ggplot Renderplot
How to Optimize the Following Code with Nested While-Loop? Multicore an Option