Datalink:
the data used
My code:
ccfsisims <- read.csv(file = "F:/Purdue University/RA_Position/PhD_ResearchandDissert/PhD_Draft/GTAP-CGE/GTAP_NewAggDatabase/NewFiles/GTAP_ConsIndex.csv", header=TRUE, sep=",", na.string="NA", dec=".", strip.white=TRUE)
ccfsirsts <- as.data.frame(ccfsisims)
ccfsirsts[6:24] <- sapply(ccfsirsts[6:24],as.numeric)
ccfsirsts <- droplevels(ccfsirsts)
ccfsirsts <- transform(ccfsirsts,sres=factor(sres,levels=unique(sres)))
library(ggplot2)
#------------------------------------------------------------------------------------------
#### Plot of food security index for Morocco and Turkey by sector
#------------------------------------------------------------------------------------------
#_Code_Begin...
datamortur <- melt(ccfsirsts[ccfsirsts$region %in% c("TUR","MAR"), ]) # Selecting regions of interest
datamortur1 <- datamortur[datamortur$variable %in% c("pFSI2"), ] # Selecting the food security index of interest
datamortur2 <- datamortur1[datamortur1$sector %in% c("wht","gro","VegtFrut","osd","OthCrop","VegtOil","XPrFood"), ] # Selecting food sectors of interest
datamortur3 <- subset(datamortur2, tradlib !="BASEDATA") # Eliminating the "BASEDATA" scenario results
allfsi.f <- datamortur3
fsi.wht <- allfsi.f[allfsi.f$sector %in% c("wht"), ]
Figure29 <- ggplot(data=fsi.wht, aes(x=factor(sres),y=value,colour=factor(tradlib)))
Figure29 + geom_line(aes(group=factor(tradlib),size=2)) + facet_grid(regionsFull~., scales="free_y", labeller=reg_labeller) + scale_colour_brewer(type = "div") +
theme(axis.text.x = element_text(colour = 'black', angle = 90, size = 13, hjust = 0.5, vjust = 0.5),axis.title.x=element_blank()) +
ylab("FSI (%Change)") + theme(axis.text.y = element_text(colour = 'black', size = 12), axis.title.y = element_text(size = 12, hjust = 0.5, vjust = 0.2)) +
theme(strip.text.y = element_text(size = 11, hjust = 0.5, vjust = 0.5, face = 'bold'))
My result:
Newresult with aes(size=2):
My question:
Is there a way to control for line width more precisely to avoid the result in the second plot? I particularly find it document-unfriendly, and more so for publishing purposes to include the plot with the newly defined line width.
best,
ismail
Whilst #Didzis has the correct answer, I will expand on a few points
Aesthetics can be set or mapped within a ggplot call.
An aesthetic defined within aes(...) is mapped from the data, and a legend created.
An aesthetic may also be set to a single value, by defining it outside aes().
As far as I can tell, what you want is to set size to a single value, not map within the call to aes()
When you call aes(size = 2) it creates a variable called `2` and uses that to create the size, mapping it from a constant value as it is within a call to aes (thus it appears in your legend).
Using size = 1 (and without reg_labeller which is perhaps defined somewhere in your script)
Figure29 +
geom_line(aes(group=factor(tradlib)),size=1) +
facet_grid(regionsFull~., scales="free_y") +
scale_colour_brewer(type = "div") +
theme(axis.text.x = element_text(
colour = 'black', angle = 90, size = 13,
hjust = 0.5, vjust = 0.5),axis.title.x=element_blank()) +
ylab("FSI (%Change)") +
theme(axis.text.y = element_text(colour = 'black', size = 12),
axis.title.y = element_text(size = 12,
hjust = 0.5, vjust = 0.2)) +
theme(strip.text.y = element_text(size = 11, hjust = 0.5,
vjust = 0.5, face = 'bold'))
and with size = 2
Figure29 +
geom_line(aes(group=factor(tradlib)),size=2) +
facet_grid(regionsFull~., scales="free_y") +
scale_colour_brewer(type = "div") +
theme(axis.text.x = element_text(colour = 'black', angle = 90,
size = 13, hjust = 0.5, vjust =
0.5),axis.title.x=element_blank()) +
ylab("FSI (%Change)") +
theme(axis.text.y = element_text(colour = 'black', size = 12),
axis.title.y = element_text(size = 12,
hjust = 0.5, vjust = 0.2)) +
theme(strip.text.y = element_text(size = 11, hjust = 0.5,
vjust = 0.5, face = 'bold'))
You can now define the size to work appropriately with the final image size and device type.
Line width in ggplot2 can be changed with argument size= in geom_line().
#sample data
df<-data.frame(x=rnorm(100),y=rnorm(100))
ggplot(df,aes(x=x,y=y))+geom_line(size=2)
Line width in ggplot2 can be changed with argument lwd= in geom_line().
geom_line(aes(x=..., y=..., color=...), lwd=1.5)
It also looks like if you just put the size argument in the geom_line() portion but without the aes() it will scale appropriately. At least it works this way with geom_density and I had the same problem.
If you want to modify the line width flexibly you can use "scale_size_manual," this is the same procedure for picking the color, fill, alpha, etc.
library(ggplot2)
library(tidyr)
x = seq(0,10,0.05)
df <- data.frame(A = 2 * x + 10,
B = x**2 - x*6,
C = 30 - x**1.5,
X = x)
df = gather(df,A,B,C,key="Model",value="Y")
ggplot( df, aes (x=X, y=Y, size=Model, colour=Model ))+
geom_line()+
scale_size_manual( values = c(4,2,1) ) +
scale_color_manual( values = c("orange","red","navy") )
Just add the size command outside the aes() function, with any fractional value desired, e.g. size = 1.5
geom_line(data,aes(x=x,y=y), size=1.5)
Related
I have a dataframe where the x value (discrete) is present and want to include on the x-axis in the plot; however, its y value is NA
I still want to show the x value even though y is NA. Is there a way to do this in ggplot2?
Currently, it simply skips the first two rows that has the NA value.
ggplot(tChartDF()[['df']], aes(
x = factor(tChartDF()[['df']][['Rare event date']], levels = unique(tChartDF()[['df']][['Rare event date']])),
y = unlist(tChartDF()[['df']][['days_between']]),
)) +
geom_hline(yintercept = unlist(tChartDF()[['timeScaleCL']]), color = input$tChartCLColour, lwd = input$tChartCLWidth) +
geom_hline(yintercept = unlist(tChartDF()[['timeScaleUL']]), linetype = 'dashed', lwd = 1, color = 'red') +
geom_hline(yintercept = unlist(tChartDF()[['timeScaleLL']]), linetype = 'dashed', lwd = 1, color = 'red') +
scale_x_discrete(expand = c(0,0)) +
theme_classic() +
geom_line(aes(group = 1), lwd = input$tChartLineWidth, color= input$tChartLineColour) +
geom_point(size = input$tChartMarkerSize, color = input$tChartMarkerColour) +
labs(title = input$tChartPlotTitle, x = input$tChartPlotXLabel, y = input$tChartPlotYLabel) +
theme(
plot.title = element_text(size = 24, face = 'bold', family = 'Arial', hjust = 0.5),
plot.margin = margin(0, 1, 0, 0, "cm"),
axis.title = element_text(size = 20, face = 'bold', family = 'Arial'),
axis.text = element_text(size = 16, face = 'bold', family = 'Arial'),
axis.text.x = element_text(angle = as.numeric(input$tChartXOrientation), vjust = 0.5),
axis.ticks.length = unit(.25, 'cm'),
) +
coord_cartesian(clip = 'off')
As seen, it only starts plotting at date: 2022/12/15 (ignoring the previous values in the table) columns y and mr have the NA values.
For the plot, I only care about the first two columns (Rare events and days_between). I tried selecting only those two columns and plotting but it still ignores the first two rows.
Desired result:
If we start with something like
mt <- mtcars
mt$mpg[c(3,6,9)] <- NA
and plot the line as in
ggplot(mt, aes(disp, mpg)) +
geom_line()
we don't see the missing points (not a surprise). We can add them this way:
transform(mt, mpg2 = ifelse(is.na(mpg), max(mpg, na.rm = TRUE) + 1, mpg)) |>
ggplot(aes(disp, mpg)) +
geom_line() +
geom_point(aes(y = mpg2), data = ~ subset(., is.na(mpg)), shape = 1)
This can easily be adapted to be at the bottom, using different shapes/colors, perhaps even on an explicitly-gray background (top/bottom ribbon).
How to place the numbers centralized and in their correct positions? I have tested numerous parameters but I have not found a solution. Everything was very confusing after coordin_flip (). Observe the image and code below.
Code:
# Package
library(ggplot2)
# Create a dataframe
RATE <- c('IgG','IgG','IgA/IgG','IgA/IgG')
GROUP <- c('Asymptomatic','Symptomatic','Asymptomatic','Symptomatic')
N_POSITIVE <- c(12,100,14,107)
PORCENT <- c(7.05, 58.8, 7.73, 59.1)
df <- data.frame(RATE, GROUP, N_POSITIVE, PORCENT)
# Plot
ggplot(df, aes(x = RATE, y = PORCENT, fill = GROUP)) +
geom_bar(stat="identity", width = 0.5) +
geom_text(aes(label=N_POSITIVE),
vjust = -0.3, color = 'black',
size = 3) +
coord_flip() +
labs(x = '', y = 'Percentage (%)\n') +
scale_fill_manual(values = c("#0073c2", "#efc000")) +
theme_classic() +
theme(
legend.position = "top",
legend.title = element_blank(),
axis.text = element_text(angle = 0, color = "black", size = 10, face = 0),
axis.title.x = element_text(angle = 0, color = "black", size = 12, face = 0))
Image:
Does this do what you want? (minus the other formatting which I left out)
ggplot(df, aes(x = PORCENT, y = RATE, fill = GROUP)) +
geom_col(width = 0.5) +
geom_text(aes(label=N_POSITIVE),
vjust = -0.3, color = 'black', hjust = 1.1,
size = 3, position = "stack")
(Note, since ggplot2 3.3.0 in March 2020, most geom's don't need coord_flip if you assign them to the axis you want. If it doesn't interpret correctly, there's also an "orientation" parameter but that doesn't seem necessary here. Also, geom_col is equal to geom_bar(stat="identity").)
I have small data frame of statistical values obtained from different method. you can download from here.Dataset is look like this:
I need to facet (two plot side by side with same y axis labels) two plot of RMSE.SD and MB variable using ggplot2 package in R like the following example figure.
I wrote this code for plotting 1 plot for RMSE.SD variable.
library(ggplot2)
comparison_korea <- read.csv("comparison_korea.csv")
ggplot(data=comparison_korea, aes(R,X))+
geom_point(color = "black", pch=17, alpha=1,na.rm=T, size=4)+
labs(title = "", y = "")+
theme(plot.title= element_text(hjust = 0.5,size = 15, vjust = 0.5, face= c("bold")),
axis.ticks.length = unit(0.2,"cm") ,
panel.border = element_rect(colour = "black", fill=NA, size=0.5),
axis.text.x = element_text(angle = 0, vjust = 0.5, size = 14, hjust = 0.5,margin=margin(4,0,0,0), colour = "black"),
axis.text.y = element_text(angle = 0, vjust = 0.5, size = 14, hjust = 1,margin=margin(0,5,0,0), colour = "black"),
plot.margin = unit(c(1, 1.5, 1, 0.5), "lines"))
You should be able to do something like this:
library(ggplot2)
ds <- read.csv("comparison_korea.csv")
dat <- data.frame(labels = as.character(ds$X),
RMSE.SD = ds$RMSE.SD,
MB = ds$MB)
dat <- reshape2::melt(dat)
ggplot(dat, aes(y = labels, x = value)) +
geom_point(shape = "+", size = 5) +
facet_wrap(~variable) +
xlab("value / reference (mm)") +
ylab("") +
theme_bw()
Datalink:
the data used
My code:
ccfsisims <- read.csv(file = "F:/Purdue University/RA_Position/PhD_ResearchandDissert/PhD_Draft/GTAP-CGE/GTAP_NewAggDatabase/NewFiles/GTAP_ConsIndex.csv", header=TRUE, sep=",", na.string="NA", dec=".", strip.white=TRUE)
ccfsirsts <- as.data.frame(ccfsisims)
ccfsirsts[6:24] <- sapply(ccfsirsts[6:24],as.numeric)
ccfsirsts <- droplevels(ccfsirsts)
ccfsirsts <- transform(ccfsirsts,sres=factor(sres,levels=unique(sres)))
library(ggplot2)
#------------------------------------------------------------------------------------------
#### Plot of food security index for Morocco and Turkey by sector
#------------------------------------------------------------------------------------------
#_Code_Begin...
datamortur <- melt(ccfsirsts[ccfsirsts$region %in% c("TUR","MAR"), ]) # Selecting regions of interest
datamortur1 <- datamortur[datamortur$variable %in% c("pFSI2"), ] # Selecting the food security index of interest
datamortur2 <- datamortur1[datamortur1$sector %in% c("wht","gro","VegtFrut","osd","OthCrop","VegtOil","XPrFood"), ] # Selecting food sectors of interest
datamortur3 <- subset(datamortur2, tradlib !="BASEDATA") # Eliminating the "BASEDATA" scenario results
allfsi.f <- datamortur3
fsi.wht <- allfsi.f[allfsi.f$sector %in% c("wht"), ]
Figure29 <- ggplot(data=fsi.wht, aes(x=factor(sres),y=value,colour=factor(tradlib)))
Figure29 + geom_line(aes(group=factor(tradlib),size=2)) + facet_grid(regionsFull~., scales="free_y", labeller=reg_labeller) + scale_colour_brewer(type = "div") +
theme(axis.text.x = element_text(colour = 'black', angle = 90, size = 13, hjust = 0.5, vjust = 0.5),axis.title.x=element_blank()) +
ylab("FSI (%Change)") + theme(axis.text.y = element_text(colour = 'black', size = 12), axis.title.y = element_text(size = 12, hjust = 0.5, vjust = 0.2)) +
theme(strip.text.y = element_text(size = 11, hjust = 0.5, vjust = 0.5, face = 'bold'))
My result:
Newresult with aes(size=2):
My question:
Is there a way to control for line width more precisely to avoid the result in the second plot? I particularly find it document-unfriendly, and more so for publishing purposes to include the plot with the newly defined line width.
best,
ismail
Whilst #Didzis has the correct answer, I will expand on a few points
Aesthetics can be set or mapped within a ggplot call.
An aesthetic defined within aes(...) is mapped from the data, and a legend created.
An aesthetic may also be set to a single value, by defining it outside aes().
As far as I can tell, what you want is to set size to a single value, not map within the call to aes()
When you call aes(size = 2) it creates a variable called `2` and uses that to create the size, mapping it from a constant value as it is within a call to aes (thus it appears in your legend).
Using size = 1 (and without reg_labeller which is perhaps defined somewhere in your script)
Figure29 +
geom_line(aes(group=factor(tradlib)),size=1) +
facet_grid(regionsFull~., scales="free_y") +
scale_colour_brewer(type = "div") +
theme(axis.text.x = element_text(
colour = 'black', angle = 90, size = 13,
hjust = 0.5, vjust = 0.5),axis.title.x=element_blank()) +
ylab("FSI (%Change)") +
theme(axis.text.y = element_text(colour = 'black', size = 12),
axis.title.y = element_text(size = 12,
hjust = 0.5, vjust = 0.2)) +
theme(strip.text.y = element_text(size = 11, hjust = 0.5,
vjust = 0.5, face = 'bold'))
and with size = 2
Figure29 +
geom_line(aes(group=factor(tradlib)),size=2) +
facet_grid(regionsFull~., scales="free_y") +
scale_colour_brewer(type = "div") +
theme(axis.text.x = element_text(colour = 'black', angle = 90,
size = 13, hjust = 0.5, vjust =
0.5),axis.title.x=element_blank()) +
ylab("FSI (%Change)") +
theme(axis.text.y = element_text(colour = 'black', size = 12),
axis.title.y = element_text(size = 12,
hjust = 0.5, vjust = 0.2)) +
theme(strip.text.y = element_text(size = 11, hjust = 0.5,
vjust = 0.5, face = 'bold'))
You can now define the size to work appropriately with the final image size and device type.
Line width in ggplot2 can be changed with argument size= in geom_line().
#sample data
df<-data.frame(x=rnorm(100),y=rnorm(100))
ggplot(df,aes(x=x,y=y))+geom_line(size=2)
Line width in ggplot2 can be changed with argument lwd= in geom_line().
geom_line(aes(x=..., y=..., color=...), lwd=1.5)
It also looks like if you just put the size argument in the geom_line() portion but without the aes() it will scale appropriately. At least it works this way with geom_density and I had the same problem.
If you want to modify the line width flexibly you can use "scale_size_manual," this is the same procedure for picking the color, fill, alpha, etc.
library(ggplot2)
library(tidyr)
x = seq(0,10,0.05)
df <- data.frame(A = 2 * x + 10,
B = x**2 - x*6,
C = 30 - x**1.5,
X = x)
df = gather(df,A,B,C,key="Model",value="Y")
ggplot( df, aes (x=X, y=Y, size=Model, colour=Model ))+
geom_line()+
scale_size_manual( values = c(4,2,1) ) +
scale_color_manual( values = c("orange","red","navy") )
Just add the size command outside the aes() function, with any fractional value desired, e.g. size = 1.5
geom_line(data,aes(x=x,y=y), size=1.5)
DataLink:
https://www.dropbox.com/s/ql5jw7eng3plrso/GTAP_MacroValueChange.csv
Code:
library(ggplot2)
library(grid)
#Upload data
ccmacrosims2 <- read.csv(file = "F:/Purdue University/RA_Position/PhD_ResearchandDissert/PhD_Draft/GTAP-CGE/GTAP_NewAggDatabase/NewFiles/GTAP_MacroValueChange.csv", header=TRUE, sep=",", na.string="NA", dec=".", strip.white=TRUE)
#Data manipulation for analysis
ccmacrorsts2 <- as.data.frame(ccmacrosims2)
ccmacrorsts2[6:10] <- sapply(ccmacrorsts2[6:10],as.numeric)
ccmacrorsts2 <- droplevels(ccmacrorsts2)
ccmacrorsts2 <- transform(ccmacrorsts2,region=factor(region,levels=unique(region)))
#Selecting data of interest
GDPDecomp1 <- melt(ccmacrorsts2[ccmacrorsts2$region %in% c("TUR","MAR"), ])
GDPDecomp2 <- GDPDecomp1[GDPDecomp1$sres %in% c("AVERAGE"), ]
GDPDecomp.f <- subset(GDPDecomp2, variable !="GDP")
#Ploting
GDPDecompPlot <- ggplot(data = GDPDecomp.f, aes(factor(region),value, fill=variable))
GDPDecompPlot + geom_bar(stat="identity", position="stack") + facet_wrap(~tradlib, scales="free_y") +
theme(axis.text.x = element_text(colour = 'black', angle = 90, size = 12, hjust = 0.5, vjust = 0.5),axis.title.x=element_blank()) +
ylab("GDP (Change in $US million)") + theme(axis.text.y = element_text(colour = 'black', size = 12), axis.title.y = element_text(size = 12)) +
theme(strip.text.x = element_text(size = 12, hjust = 0.5, vjust = 0.5, face = 'bold'))
Issue at hand:
The barplot using ggplot (see below)
excel_barplot:
It seems that the plot does not really represent correctly the values of the data. What I am looking for is something like what we get from excel_barplot_sample. For instance, comparing the panel "TRLIBEU" under ggplot with its counterpart using excel, one can clearly notice that the ggplot does not capture the values in the data correctly when stacking.
Any help on how to correct for the discrepancy?
Thanks in advance
If you need to stack bars in ggplot2 with negative values then for better result you should make two new data frames - one for positive values and second for negative values.
GDPDecomp.f.pos<-GDPDecomp.f[GDPDecomp.f$value>0,]
GDPDecomp.f.neg<-GDPDecomp.f[GDPDecomp.f$value<0,]
Then use each data frame in its own geom_bar() call.
ggplot()+
geom_bar(data=GDPDecomp.f.pos,aes(x=factor(region),y=value,fill=variable),stat="identity")+
geom_bar(data=GDPDecomp.f.neg,aes(x=factor(region),y=value,fill=variable),stat="identity")+
facet_wrap(~tradlib, scales="free_y") +
theme(axis.text.x = element_text(colour = 'black', angle = 90, size = 12, hjust = 0.5, vjust = 0.5),axis.title.x=element_blank()) +
ylab("GDP (Change in $US million)") + theme(axis.text.y = element_text(colour = 'black', size = 12), axis.title.y = element_text(size = 12)) +
theme(strip.text.x = element_text(size = 12, hjust = 0.5, vjust = 0.5, face = 'bold'))