Overlapped data with messed up axises using facet_grid in R - r

I am using facet grid to generate neat presentations of my data.
Basically, my data frame has four columns:
idx, density, marker, case.
There are 5 cases, each case corresponds to 5 markers, and each marker corresponds to multiple idx, each idx corresponds to one density.
The data is uploaded here:
data frame link
I tried to use facet_grid to achieve my goal, however, I obtained a really messed up graph:
The x-axis and y-axis are messed up, the codes are:
library(ggplot2)
library(cowplot)
plot.density <-
ggplot(df_densityWindow, aes(x = idx, y = density)) +
geom_col() +
facet_grid(marker ~ case, scales = 'free') +
background_grid(major = 'y', minor = "none") + # add thin horizontal lines
panel_border() # and a border around each panel
plot(plot.density)
EDIT:
I reupload the file, now it should be work:
download file here

All 4 columns have been read as factors. This is an issue from however you loaded the data into R. Take a look at:
df <- readRDS('df.rds')
str(df)
'data.frame': 52565 obs. of 4 variables:
$ idx : Factor w/ 4712 levels "1","10","100",..: 1 1112 2223 3334 3546 3657 3768 3879 3990 2 ...
$ density: Factor w/ 250 levels "1022.22222222222",..: 205 205 204 203 202 201 199 198 197 197 ...
$ marker : Factor w/ 5 levels "CD3","CD4","CD8",..: 1 1 1 1 1 1 1 1 1 1 ...
$ case : Factor w/ 5 levels "Case_1","Case_2",..: 1 1 1 1 1 1 1 1 1 1 ...
Good news is that you can fix it with:
df$idx <- as.integer(as.character(df$idx))
df$density <- as.numeric(as.character(df$density))
Although you should look into how you are loading the data, to avoid future.
As another trick, try the above code without using the as.character calls, and compare the differences.

As already explained by MrGumble, the idx and density variables are of type factor but should be plotted as numeric.
The type.convert() function does the data conversion in one go:
library(ggplot2)
library(cowplot)
ggplot(type.convert(df_densityWindow), aes(x = idx, y = density)) +
geom_col() +
facet_grid(marker ~ case, scales = 'free') +
background_grid(major = 'y', minor = "none") + # add thin horizontal lines
panel_border() # and a border around each panel

Related

2d plot with 3rd variable as color in RStudio

I have a dataset as CSV with three columns:
timestamp (e.g. 2018/12/15)
keyword (e.g. "hello")
count (e.g. 7)
I want one plot where all the lines of the same keyword are connected with each other and timestamp is on the X- and count is on the Y- axis. I would like each keyword to have a different color for its line and the line being labeled with the keyword.
The CSV has only ~30.000 rows and R runs on a dedicated machine. Performance can be ignored.
I tried various approaches with mathplot and ggplot in this forum, but didn't get it to work with my own data.
What is the easiest solution to do this in R?
Thanks!
EDIT:
I tried customizing Romans code and tried the following:
`csvdata <- read.csv("c:/mydataset.csv", header=TRUE, sep=",")
time <- csvdata$timestamp
count <- csvdata$count
keyword <- csvdata$keyword
time <- rep(time)
xy <- data.frame(time, word = c(keyword), count, lambda = 5)
library(ggplot2)
ggplot(xy, aes(x = time, y = count, color = keyword)) +
theme_bw() +
scale_color_brewer(palette = "Set1") + # choose appropriate palette
geom_line()`
This creates a correct canvas, but no points/lines in it...
DATA:
head(csvdata)
keyword count timestamp
1 non-distinct-word 3 2018/08/09
2 non-distinct-word 2 2018/08/10
3 non-distinct-word 3 2018/08/11
str(csvdata)
'data.frame': 121 obs. of 3 variables:
$ keyword : Factor w/ 10 levels "non-distinct-word",..: 5 5 5 5 5 5 5 5 5 5 ...
$ count : int 3 2 3 1 6 6 2 3 2 1 ...
$ timestamp: Factor w/ 103 levels "2018/08/09","2018/08/10",..: 1 2 3 4 5 6 7 8 9 10 ...
Something like this?
# Generate some data. This is the part poster of the question normally provides.
today <- as.Date(Sys.time())
time <- rep(seq.Date(from = today, to = today + 30, by = "day"), each = 2)
xy <- data.frame(time, word = c("hello", "world"), count = rpois(length(time), lambda = 5))
library(ggplot2)
ggplot(xy, aes(x = time, y = count, color = word)) +
theme_bw() +
scale_color_brewer(palette = "Set1") + # choose appropriate palette
geom_line()

Reasons that ggplot2 legend does not appear [duplicate]

This question already has answers here:
Add legend to ggplot2 line plot
(4 answers)
Closed 2 years ago.
I was attempting (unsuccessfully) to show a legend in my R ggplot2 graph which involves multiple plots. My data frame df and code is as follows:
Individuals Mod.2 Mod.1 Mod.3
1 2 -0.013473145 0.010859793 -0.08914021
2 3 -0.011109863 0.009503278 -0.09049672
3 4 -0.006465788 0.011304668 -0.08869533
4 5 0.010536718 0.009110458 -0.09088954
5 6 0.015501212 0.005929766 -0.09407023
6 7 0.014565584 0.005530390 -0.09446961
7 8 -0.009712516 0.012234843 -0.08776516
8 9 -0.011282278 0.006569570 -0.09343043
9 10 -0.011330579 0.003505439 -0.09649456
str(df)
'data.frame': 9 obs. of 4 variables:
$ Individuals : num 2 3 4 5 6 7 8 9 10
$ Mod.2 : num -0.01347 -0.01111 -0.00647 0.01054 0.0155 ...
$ Mod.1 : num 0.01086 0.0095 0.0113 0.00911 0.00593 ...
$ Mod.3 : num -0.0891 -0.0905 -0.0887 -0.0909 -0.0941 ...
ggplot(df, aes(df$Individuals)) +
geom_point(aes(y=df[,2]), colour="red") + geom_line(aes(y=df[,2]), colour="red") +
geom_point(aes(y=df[,3]), colour="lightgreen") + geom_line(aes(y=df[,3]), colour="lightgreen") +
geom_point(aes(y=df[,4]), colour="darkgreen") + geom_line(aes(y=df[,4]), colour="darkgreen") +
labs(title = "Modules", x = "Number of individuals", y = "Mode")
I looked up the following stackflow threads, as well as Google searches:
Merging ggplot2 legend
ggplot2 legend not showing
`ggplot2` legend not showing label for added series
ggplot2 legend for geom_area/geom_ribbon not showing
ggplot and R: Two variables over time
ggplot legend not showing up in lift chart
Why ggplot2 legend not show in the graph
ggplot legend not showing up in lift chart.
This one was created 4 days ago
This made me realize that making legends appear is a recurring issue, despite the fact that legends usually appear automatically.
My first question is what are the causes of a legend to not appear when using ggplot? The second is how to solve these causes. One of the causes appears to be related to multiple plots and the use of aes(), but I suspect there are other reasons.
colour= XYZ should be inside the aes(),not outside:
geom_point(aes(data, colour=XYZ)) #------>legend
geom_point(aes(data),colour=XYZ) #------>no legend
Hope it helps, it took me a hell long way to figure out.
You are going about the setting of colour in completely the wrong way. You have set colour to a constant character value in multiple layers, rather than mapping it to the value of a variable in a single layer.
This is largely because your data is not "tidy" (see the following)
head(df)
x a b c
1 1 -0.71149883 2.0886033 0.3468103
2 2 -0.71122304 -2.0777620 -1.0694651
3 3 -0.27155800 0.7772972 0.6080115
4 4 -0.82038851 -1.9212633 -0.8742432
5 5 -0.71397683 1.5796136 -0.1019847
6 6 -0.02283531 -1.2957267 -0.7817367
Instead, you should reshape your data first:
df <- data.frame(x=1:10, a=rnorm(10), b=rnorm(10), c=rnorm(10))
mdf <- reshape2::melt(df, id.var = "x")
This produces a more suitable format:
head(mdf)
x variable value
1 1 a -0.71149883
2 2 a -0.71122304
3 3 a -0.27155800
4 4 a -0.82038851
5 5 a -0.71397683
6 6 a -0.02283531
This will make it much easier to use with ggplot2 in the intended way, where colour is mapped to the value of a variable:
ggplot(mdf, aes(x = x, y = value, colour = variable)) +
geom_point() +
geom_line()
ind = 1:10
my.df <- data.frame(ind, sample(-5:5,10,replace = T) ,
sample(-5:5,10,replace = T) , sample(-5:5,10,replace = T))
df <- data.frame(rep(ind,3) ,c(my.df[,2],my.df[,3],my.df[,4]),
c(rep("mod.1",10),rep("mod.2",10),rep("mod.3",10)))
colnames(df) <- c("ind","value","mod")
Your data frame should look something likes this
ind value mod
1 5 mod.1
2 -5 mod.1
3 3 mod.1
4 2 mod.1
5 -2 mod.1
6 5 mod.1
Then all you have to do is :
ggplot(df, aes(x = ind, y = value, shape = mod, color = mod)) +
geom_line() + geom_point()
I had a similar problem with the tittle, nevertheless, I found a way to show the title: you can add a layer using
ggtitle ("Name of the title that you want to show")
example:
ggplot(data=mtcars,
mapping = aes(x=hp,
fill = factor(vs)))+
geom_histogram(bins = 9,
position = 'identity',
alpha = 0.8, show.legend = T)+
labs(title = 'Horse power',
fill = 'Vs Motor',
x = 'HP',
y = 'conteo',
subtitle = 'A',
caption = 'B')+
ggtitle("Horse power")

Combine Stacked bars and Lines into a same graph with categorical variables

I have the following dataframe:
library(rsdmx)
library(dplyr)
library(countrycode)
dt<-as.data.frame(readSDMX("http://widukind-api.cepremap.org/api/v1/sdmx/IMF/data/IFS/..Q.BFPA-BP6-USD"))
AP<-rename(dt, Country=WIDUKIND_NAME, Year=TIME_PERIOD,A.PI.T=OBS_VALUE)
AP<-AP[c("Country","REF-AREA","Year","A.PI.T")]
AP$Country<-countrycode(AP$`REF-AREA`, "imf","iso3c")
AP$A.PI.T<-as.numeric((as.character(AP$A.PI.T)))
AP$Country[which(AP$`REF-AREA` == 163)] <- "EURO"
AP$Country[which(AP$`REF-AREA` == 967)] <- "RKS"
AP$Country[which(AP$`REF-AREA` == 355)] <- "CUW+SMX"
AP$Country<-as.factor(AP$Country)
AP$v1<-AP$A.PI.T/2
AP$v2<-AP$v1
str(AP)
'data.frame': 11452 obs. of 6 variables:
$ Country : Factor w/ 142 levels "ABW","AFG","ALB",..: 2 2 2 2 2 2 2 2 2 2 ...
$ REF-AREA: Factor w/ 142 levels "512","299","258",..: 1 1 1 1 1 1 1 1 1 1 ...
$ Year : chr "2008-Q2" "2008-Q3" "2008-Q4" "2009-Q1" ...
$ A.PI.T : num -113146 -321591 -1000741 16685590 540591 ...
$ v1 : num -56573 -160796 -500370 8342795 270295 ...
$ v2 : num -56573 -160796 -500370 8342795 270295 ...
As you see I have three numerical variables and another variables Year supposed to capture dates. In the meantime, There is a categorical variable Country.
My scope is to create charts for EVERY category in Country.
The type of chart I want is a mixure of stacked bar and a line type chart, where I want to have an option to pre-specify the range of dates, for example I want from 2012-Q1 to 2015Q3. To give you a better idea of how the chart should look like, I did an example in Excel, for the Euro in Country
In the ideal case, I want to export all the charts that should be created for every level in Country into a convenient form where non-R users can use and explore.
Do you want something like the following (shown only for EURO and UKR):
library(reshape2)
df <- melt(AP, id=1:3)
library(ggplot2)
ggplot(df[df$Country %in% c('EURO', 'UKR'),], aes(Year, value, fill=variable)) +
geom_bar(stat='identity') +
theme(axis.text.x = element_text(angle=90, vjust = 0.5)) +
facet_wrap(~Country, scales='free')

Reorder stacks in horizontal stacked barplot (R)

I'm trying to make a horizontal stacked barplot using ggplot. Below are the actual values for three out of 300 sites in my data frame. Here's where I've gotten to so far, using info pulled from these previous questions which I admit I may not have fully understood.
df <- data.frame(id=c("AR001","AR001","AR001","AR001","AR002","AR002","AR002","AR003","AR003","AR003","AR003","AR003"),
landuse=c("agriculture","developed","forest","water","agriculture","developed","forest","agriculture","developed","forest","water","wetlands"),
percent=c(38.77,1.76,59.43,0.03,69.95,0.42,29.63,65.4,3.73,15.92,1.35,13.61))
df
id landuse percent
1 AR001 agriculture 38.77
2 AR001 developed 1.76
3 AR001 forest 59.43
4 AR001 water 0.03
5 AR002 agriculture 69.95
6 AR002 developed 0.42
7 AR002 forest 29.63
8 AR003 agriculture 65.40
9 AR003 developed 3.73
10 AR003 forest 15.92
11 AR003 water 1.35
12 AR003 wetlands 13.61
str(df)
'data.frame': 12 obs. of 3 variables:
$ id : Factor w/ 3 levels "AR001","AR002",..: 1 1 1 1 2 2 2 3 3 3 ...
$ landuse: Factor w/ 5 levels "agriculture",..: 1 2 3 4 1 2 3 1 2 3 ...
$ percent: num 38.77 1.76 59.43 0.03 69.95 ...
df <- transform(df,
landuse.ord = factor(
landuse,
levels=c("agriculture","forest","wetlands","water","developed"),
ordered =TRUE))
cols <- c(agriculture="maroon",forest="forestgreen",
wetlands="gold", water="dodgerblue", developed="darkorchid")
ggplot(df,aes(x = id, y = percent, fill = landuse.ord, order=landuse.ord)) +
geom_bar(position = "stack",stat = "identity", width=1) +
coord_flip() +
scale_fill_manual(values = cols)
which produces this graph.
What I would like to do is to reorder the bars so that they are in descending order by value for the agriculture category - in this example AR002 would be at the top, followed by AR003 then AR001. I tried changing the contents of aes to aes(x = reorder(landuse.ord, percent), but that eliminated the stacking and seemed to have maybe summed the percentages for each land use category:
I would like to have the stacks in order, from left to right: agriculture, forest, wetlands, water, developed. I tried doing that with the transform part of the code, which put it in the correct order in the legend, but not in the plot itself?
Thanks in advance... I have made a ton of progress based on answers to other peoples' questions, but seem to now be stuck at this point!
Update: here is the finished graph for all 326 sites!
Ok based on your comments, I believe this is your solution. Place these lines after cols<-...:
#create df to sort by argiculture's percentage
ag<-filter(df, landuse=="agriculture")
#use the df to sort and order df$id's levels
df$id<-factor(df$id, levels=ag$id[order(ag$percent)], ordered = TRUE)
#sort df, based on ordered ids and ordered landuse
df<-df[order(df$id, df$landuse.ord),]
ggplot(df,aes(x = id, y = percent, fill = landuse.ord, order=landuse.ord)) +
geom_bar(position = "stack",stat = "identity", width=1) +
coord_flip() +
scale_fill_manual(values = cols)
The comments should clarify each of the lines purposes. This will reorder your original data frame, if that is a problem I would create a copy and then operate on the new copy.

Creating a line graph (mean), arranged by facets, with standard error of mean error bars: ggplot

Hi Stack Overflow community,
I have a dataset:
conc branch length stage factor
1 1000 3 573.5 e14 NRG4
2 1000 7 425.5 e14 NRG4
3608 1000 44 5032.0 P10 NRG4
3609 1000 0 0.0 P10 NRG4
FYI
> str(dframe1)
'data.frame': 3940 obs. of 5 variables:
$ conc : Factor w/ 6 levels "0","1","10","100",..: 6 6 6 6 6 6 6 6 6 6 ...
$ branch: int 3 7 5 0 1 0 0 4 1 1 ...
$ length: num 574 426 204 0 481 ...
$ stage : Factor w/ 8 levels "e14","e16","e18",..: 1 1 1 1 1 1 1 1 1 1 ...
$ factor: Factor w/ 2 levels "","NRG4": 2 2 2 2 2 2 2 2 2 2 ...
I would like to create facetted line graphs, plotting the mean +/- standard error of the mean
I have tried experimenting and building a ggplot from others (here and on the web).
I have successfully used scripts that will make bargraphs this way:
errbar.ggplot.facets <- ggplot(dframe1, aes(x = conc, y = length))
### function to calculate the standard error of the mean
se <- function(x) sd(x)/sqrt(length(x))
### function to be applied to each panel/facet
my.fun <- function(x) {
data.frame(ymin = mean(x) - se(x),
ymax = mean(x) + se(x),
y = mean(x))}
g.err.f <- errbar.ggplot.facets +
stat_summary(fun.y = mean, geom = "bar",
fill = clrs.hcl(48)) +
stat_summary(fun.data = my.fun, geom = "linerange") +
facet_wrap(~ stage) +
theme_bw()
print(g.err.f)
Source: http://teachpress.environmentalinformatics-marburg.de/2013/07/creating-publication-quality-graphs-in-r-7/
In fact, I have created facetted line graphs with this script:
`ggplot(data=dframe1, aes(x=conc, y = length, group = stage)) +
geom_line() + facet_wrap(~stage)`
image: postimg.org/image/ebpdc0sb7
However, I used a transformed dataset of only means, SEM in another column, but I don't know how to add them.
Given the complexity (for me) of the bargraphs + error line scripts above, I have not yet been able to integrate/synthesize these into something I need.
In this case, the colour is not important to have.
P.S. I apologise for the long thread (and perhaps the overkill on some details). This is my first online R question, so not sure of correct etiquette. Thank you all in advance for being so helpful!
Darian
In case your dataframe has a column for the mean and the se you could do something like this:
library("dplyr")
library("ggplot2")
# Create a dummydataframe with columns mean and se
df <- mtcars %>%
group_by(gear, cyl) %>%
summarise(mean_mpg = mean(mpg), se_mpg = se(mpg))
ggplot(df, aes(x = gear, y = mean_mpg)) +
geom_bar(stat = "identity") +
geom_errorbar(aes(ymin = mean_mpg - se_mpg, ymax = mean_mpg + se_mpg)) +
facet_wrap(~cyl)

Resources