How can I fix the following code
alpha <- 1
draws <- 15
dimen <- 10
require(MCMCpack)
x <- rdirichlet(draws, rep(alpha, dimen))
require(ggplot2)
dat <- data.frame(item=factor(rep(1:10,15)),
draw=factor(rep(1:15,each=10)),
value=as.vector(t(x)))
ggplot(dat,aes(x=item,y=value,ymin=0,ymax=value)) +
geom_point(colour=I("blue")) +
geom_linerange(colour=I("blue")) +
facet_wrap(~draw,ncol=5) +
scale_y_continuous(lim=c(0,1)) +
opts(panel.border=theme_rect())
to not to get this empty plot:
I assume you get the following error message:
'opts' is deprecated. Use 'theme' instead. (Deprecated; last used in version 0.9.1)
theme_rect is deprecated. Use 'element_rect' instead. (Deprecated; last used in version 0.9.1)
If so, this should be stated in your question.
Using the current version of ggplot2 (0.9.3.1) and theme() instead of opts(), this script:
ggplot(data = dat, aes(x = item, y = value, ymin = 0, ymax = value)) +
geom_point(colour = "blue") +
geom_linerange(colour = "blue") +
facet_wrap(~draw, ncol = 5) +
scale_y_continuous(lim = c(0, 1)) +
theme_bw() +
theme(panel.border = element_rect(colour = "black"))
...gives this plot:
Is this what you want?
You may also wish to check the scales argument in ?facet_wrap, and coord_cartesian as an alternative to set limits in scale_y_continuous
Related
I am currently plotting data using the ggpubr package in R (based on ggplot2). When I plot the means of two conditions including standard errors, the y-axis should be limited from 1 to 7, which I indicate using:
p <- ggline(data, x = "condition", y = "measure",
add = c("mean_se"),
ylab = "Measure")
ggpar(y, ylim = c(1, 7), ticks=T, yticks.by = 1)
In the final plot, however, the y-axis shows only values from 1 to 6
I tried to plot the same data using native ggplot2, but the problem persists, once I change the layout.
For ggplot2 I used:
p <- ggplot(data, aes(x=condition, y=measure)) +
geom_line() +
geom_point()+
geom_errorbar(aes(ymin=measure-se, ymax=measure+se), width=.2, position=position_dodge(0.05)) +
ylab("measure") +
xlab("Condition")
p + scale_y_continuous(name="measure", limits=c(1, 7), breaks=c(1:7))
p + theme_classic()
It would be great if someone could help me with this issue.
Edit:
as suggested in the comments, here is the data I am trying to plot using ggplot2:
structure(list(condition = structure(3:4, .Label = c("IC", "SC",
"ILC", "SLC"), class = "factor"), measure = c(4.10233918128655, 3.83040935672515
), se = c(0.235026318386523, 0.216811675834834)), class = "data.frame", row.names = c(NA,
-2L))
I think I got something resembling your plot with correct y-axes with the following code:
ggplot(data, aes(x = condition, y = measure)) +
geom_point() +
geom_errorbar(aes(ymin = measure-se, ymax = measure+se),
width = .2, position = position_dodge(0.05)) +
# Group prevents geom_line interpreting each x-axis point as it's own group
geom_line(aes(group = rep(1, nrow(data)))) +
xlab("Condition") +
# Expand is optional, it prevents padding beyond 1 and 7
scale_y_continuous(name = "measure",
limits = c(1, 7),
breaks = 1:7,
expand = c(0,0)) +
theme_classic()
The solution is much more trivial. You were doing everything right! Except for one clerical error. Here is what was happening:
First, you generate your initial plot, fine.
p <- ggplot(data, aes(x=condition, y=measure)) +
geom_line() + geom_point() +
geom_errorbar(aes(ymin=measure-se, ymax=measure+se),
width=.2, position=position_dodge(0.05)) +
ylab("measure") +
xlab("Condition")
This plot does not have the limits. When you add the limits and display it, the scales are correct:
p + scale_y_continuous(name="measure", limits=c(1, 7), breaks=c(1:7))
However, note that p did not change! You did not store the result of adding the limits to p. Therefore, p is still without the scale_y_continuous. No wonder then that when you type
p + theme_classic()
...the limits are gone. However, if you try
p <- p + scale_y_continuous(name="measure", limits=c(1, 7), breaks=c(1:7))
p + theme_classic()
everything will be correct.
I am new to R, I have a plot that shows the percprof stats in each state of all counties, but when I am trying to add a mean value to each plot, it is not working:
library(ggplot2)
data(midwest)
percprof_mean <- sd(midwest$percprof)
ggplot(midwest, aes(x=percprof, y=..density..))
+ geom_histogram(binwidth = 0.5, color = "white") + facet_grid(state ~.)
+ stat_summary(fun.y=mean,geom="line",lwd=2,aes(group=1))
did I use stat_summary function wrong here? I get error says:
Error: stat_summary requires the following missing aesthetics: y
plyr based solution.
library(ggplot2)
library(plyr)
data(midwest)
nn <- ddply(midwest, "state", transform,
state_mean = mean(percprof))
ggplot(nn) +
geom_histogram(aes(percprof, y=..density..),binwidth = 0.5, color = "white") +
geom_vline(aes(xintercept = state_mean),data=nn,linetype = 5) + facet_grid(state~.)
I am trying to set up a graph where the size of the point is smaller if n == 0 than n > 0. The code works until I add a legend. Here is my code that works:
ggplot(len.oo, aes(x = TCL, y = n, colour = worm, shape = worm)) + ylim(0, 20) +
geom_point(size = ifelse(len.oo$n == 0, 2, 4)) +
theme_bw() + xlab(expression(~italic("O. obscurus")~"TCL (mm)")) + ylab("Abundance") +
theme(legend.title=element_blank(), legend.position="none")
that gives me:
as soon as i add a legend it gives me an error. code with legend:
ggplot(len.oo, aes(x = TCL, y = n, colour = worm, shape = worm)) + ylim(0, 20) +
geom_point(size = ifelse(len.oo$n == 0, 2, 4)) +
theme_bw() + xlab(expression(~italic("O. obscurus")~"TCL (mm)")) + ylab("Abundance") +
theme(legend.title=element_blank(), legend.position=c(0.2, 0.8)) + guides(size=FALSE)
gives me the error:
Error: Aesthetics must be either length 1 or the same as the data (3):
size
I've also tried position = "top" and the like to have the legend outside the plot and without the guides(size=FALSE)
I could easily make the graph without the legend and then make the legend without the size difference and use other software to copy and paste the legend on the image, but I would like to do all this in R.
The problem lies here: geom_point(size = ifelse(len.oo$n == 0, 2, 4))
I can't give you a direct solution because no data was provided, but I'd suggest adding a variable in your len.oo dataframe so that this variable (let's say you call it size_n) is either a 2 or a 4 if n is equal to 0 and then change the ggplot layer to geom_point(aes(size = size_n)).
You can create this new variable with the following code:
library(dplyr)
len.oo <- mutate(len.oo, size_n = ifelse(n == 0, 2, 4))
I made the following plot in Excel:
But then I thought I would make it prettier by using ggplot. I got this far:
If you're curious, the data is based on my answer here, although it doesn't really matter. The plot is a standard ggplot2 construct with some prettification, and the thick line for the x-axis through the middle is achieved with p + geom_hline(aes(yintercept=0)) (p is the ggplot object).
I feel that the axis configuration in the Excel plot is better. It emphasizes the 0 line (important when the data is money) and finding intercepts is much easier since you don't have to follow lines from all the way at the bottom. This is also how people draw axes when plotting on paper or boards.
Can the axis be moved like this in ggplot as well? I want not just the line, but the tick labels as well moved. If yes, how? If no, is the reason technical or by design? If by design, why was the decision made?
try this,
shift_axis <- function(p, y=0){
g <- ggplotGrob(p)
dummy <- data.frame(y=y)
ax <- g[["grobs"]][g$layout$name == "axis-b"][[1]]
p + annotation_custom(grid::grobTree(ax, vp = grid::viewport(y=1, height=sum(ax$height))),
ymax=y, ymin=y) +
geom_hline(aes(yintercept=y), data = dummy) +
theme(axis.text.x = element_blank(),
axis.ticks.x=element_blank())
}
p <- qplot(1:10, 1:10) + theme_bw()
shift_axis(p, 5)
I tried to change the theme's axis.text.x,but only can change hjust.
So I think you can delete axis.text.x,then use geom_text() to add.
For example:
test <- data.frame(x=seq(1,5), y=seq(-1,3))
ggplot(data=test, aes(x,y)) +
geom_line() +
theme(axis.text.x=element_blank(), axis.ticks.x=element_blank()) +
geom_text(data=data.frame(x=seq(1,5), y=rep(0,5)), label=seq(1,5), vjust=1.5)
Maybe these codes are useful.
just to complete baptiste's excellent answer with the equivalent for moving the y axis:
shift_axis_x <- function(p, x=0){
g <- ggplotGrob(p)
dummy <- data.frame(x=x)
ax <- g[["grobs"]][g$layout$name == "axis-l"][[1]]
p + annotation_custom(grid::grobTree(ax, vp = grid::viewport(x=1, width = sum(ax$height))),
xmax=x, xmin=x) +
geom_vline(aes(xintercept=x), data = dummy) +
theme(axis.text.y = element_blank(),
axis.ticks.y=element_blank())
}
As alistaire commented it can be done using geom_hline and geom_text as shown below.
df <- data.frame(YearMonth = c(200606,200606,200608,200701,200703,200605),
person1 = c('Alice','Bob','Alice','Alice','Bob','Alice'),
person2 = c('Bob','Alice','Bob','Bob','Alice','Bob'),
Event = c('event1','event2','event3','event3','event2','event4')
)
df$YM <- as.Date(paste0("01",df$YearMonth), format="%d%Y%m")
rangeYM <- range(df$YM)
ggplot()+geom_blank(aes(x= rangeYM, y = c(-1,1))) + labs(x = "", y = "") +
theme(axis.ticks = element_blank()) +
geom_hline(yintercept = 0, col = 'maroon') +
scale_x_date(date_labels = '%b-%y', date_breaks = "month", minor_breaks = NULL) +
scale_y_continuous(minor_breaks = NULL) +
geom_text(aes(x = df$YM, y = 0, label = paste(format(df$YM, "%b-%y")), vjust = 1.5), colour = "#5B7FA3", size = 3.5, fontface = "bold")
I have data with the word alpha in it, and I'd like to use ggplot2 to render the alpha in the breaks as the symbol.
df <- data.frame(Method = c("Method (alpha = 0.01)", "Method (alpha = 0.05)"),
Value = c(2,3))
ggplot(df, aes(x = Method,
y = Value)) +
geom_point()
I couldn't find this on the site, but I don't think it will be that difficult a question. I can get single values in breaks to work using the expression command in ggplot2::xlab, etc., but I can't figure out how to create a vector of expressions. For example, the code
c(expression("Method (alpha = 0.01)"),
+ expression("Method (alpha = 0.05)"))
gives as output
expression("Method (alpha = 0.01)", "Method (alpha = 0.05)")
You can use parse as in the following possibilities. I think this is easier than having to write out lists of expressions.
Edit
To increase the space between 'Method' and the rest,
df$Method <- gsub("Method", "Method~", as.character(df$Method))
Then, plot
ggplot(df, aes(x = Method, y = Value)) +
geom_point() +
scale_x_discrete(labels = parse(text=gsub('=','==',as.character(df$Method))))
or
ggplot(df, aes(x = Method, y = Value)) +
geom_point() +
scale_x_discrete(labels = parse(text=paste("alpha", c(0.01, 0.05), sep="==")))
The result from the first one,