simple boxplot using qplot/ggplot2 - r

This is my first post, so go easy. Up until now (the past ~5 years?) I've been able to either tweak my R code the right way or find an answer on this or various other sites. Trust me when I say that I've looked for an answer!
I have a working script to create the attached boxplot in basic R.
http://i.stack.imgur.com/NaATo.jpg
This is fine, but I really just want to "jazz" it up in ggplot, for vain reasons.
I've looked at the following questions and they are close, but not complete:
Why does a boxplot in ggplot requires axis x and y?
How do you draw a boxplot without specifying x axis?
My data is basically like "mtcars" if all the numerical variables were on the same scale.
All I want to do is plot each variable on the same boxplot, like the basic R boxplot I made above. My y axis is the same continuous scale (0 to 1) for each box and the x axis simply labels each month plus a yearly average (think all the mtcars values the same on the y axis and the x axis is each vehicle model). Each box of my data represents 75 observations (kind of like if mtcars had 75 different vehicle models), again all the boxes are on the same scale.
What am I missing?

Though I don't think mtcars makes a great example for this, here it is:
First, we make the data (hopefully) more similar to yours by using a column instead of rownames.
mt = mtcars
mt$car = row.names(mtcars)
Then we reshape to long format:
mt_long = reshape2::melt(mt, id.vars = "car")
Then the plot is easy:
library(ggplot2)
ggplot(mt_long, aes(x = variable, y = value)) +
geom_boxplot()
Using ggplot all but requires data in "long" format rather than "wide" format. If you want something to be mapped to a graphical dimension (x-axis, y-axis, color, shape, etc.), then it should be a column in your data. Luckily, it's usually quite easy to get data in the right format with reshape2::melt or tidyr::gather. I'd recommend reading the Tidy Data paper for more on this topic.

Related

Plot or highlight additional values in facet wrap graph

I have some time series data, I've used a few functions to find specific x,y coordinates and wish to have them highlighted on the facet plot I've created. Not even sure if it's possible.
# create sample data
t<-seq(1:100)
a<-rnorm(1:100)
b<-rnorm(1:100)
c<-rnorm(1:100)
g <-as.data.frame(cbind(t,a,b,c))
g <- melt(g,id="t")
# current facet graph
ggplot(g,aes(x=t,y=value,color=variable))+
geom_point()+
facet_wrap(~variable)
This looks along the lines of what I've got right now. But I've also got the additional data below, which is a dataframe of x,y coordinates.
# sample data with x,y coords
x1 <- c(10,11,15)
y1 <- c(5,6,9)
x2 <- c(50,41,35)
y2 <- c(25,27,19)
xy<-rbind(x1,y1,x2,y2)
colnames(xy)<-c("a","b","c")
I'm not sure how to make this happen. I'd like the coordinates to be graphed in their individual plots.
Thanks for the help above, as you guys suspected the format of my data was incorrect. I'm still a novice and so collecting and formatting the data is often not as straightforward.
#the format of my 'primary' dataframe
t<-seq(1:100)
a<-rnorm(1:100)
b<-rnorm(1:100)
c<-rnorm(1:100)
g <-as.data.frame(cbind(t,a,b,c))
g <- melt(g,id="t")
#and then converting the original dataframe above to something that matches
xy<-data.frame(t = c(10,11,15,50,41,35),variable=c('a','b','c'),value = c(5,6,9,25,27,19))
as soon as I converted the df to the correct format it became much easier to fiddle around with.
ggplot(g,aes(x=t,y=value,color=variable))+
geom_point()+
geom_point(data=xy,size=4) +
facet_wrap(~variable)
The below picture shows the result. Perhaps a better title to the question would be Plot multiple dataframes on a single facet

Avoid overlapping x-axis labels with ggplot? [duplicate]

I'm having some trouble with qplot in R. I am trying to plot data from a data frame. When I execute the command below the plot gets bunched up on the left side (see the image below). The data frame only has 963 rows so I don't think size is the issue, but I can use the same command on a smaller data frame and it looks fine. Any ideas?
library(ggplot2)
qplot(x=variable,
y=value,
data=data,
color=Classification,
main="Average MapQ Scores")
Or similarly:
ggplot(data = data, aes(x = variable, y = value, color = Classification) +
geom_point()
Your column value is likely a factor, when it should be a numeric. This causes each categorical value of value to be given its own entry on the y-axis, thus producing the effect you've noticed.
You should coerce it to be a numeric
data$value <- as.numeric(as.character(data$value))
Note that there is probably a good reason it has been interpreted as a factor and not a numeric, possibly because it has some entries that are not pure numeric values (maybe 1,000 or 1000 m or some other character entry among the numbers). The consequence of the coercion may be a loss of information, so be warned or cleanse the data thoroughly.
Also, you appear to have the same problem on the x-axis.

Display maximum frequency point of each bin in ggplot2 stat_binhex

I have a data set in which a coordinate can be repeated several times.
I want to make a hexbinplot displaying the maximum number of times a coordinate is repeated within that bin. I am using R and I would prefer to make it with ggplot so the graph is consistent with other graphs in the same report.
Minimum working example (the bins display the count not the max):
library(ggplot2)
library(data.table)
set.seed(41)
dat<-data.table(x=sample(seq(-10,10,1),1000,replace=TRUE),
y=sample(seq(-10,10,1),1000,replace=TRUE))
dat[,.N,by=c("x","y")][,max(N)]
# No bin should be over 9
p1 <- ggplot(dat,aes(x=x,y=y))+stat_binhex(bins=10)
p1
I believe the approach should be related to this question:
calculating percentages for bins in ggplot2 stat_binhex but I am not sure how to adapt it to my case.
Also, I am concerned about this issue ggplot2: ..count.. not working with stat_bin_hex anymore as it can make my objective harder than what I initially thought.
Is it possible to make the bins display the maximum number of times a point is repeated?
I think, after playing with the data a bit more, I now understand. Each bin in the plot represents multiple points, e.g., (9,9);(9,10)(10,9);(10,10) are all in a single bin in the plot. I must caution that this is the expected behavior. It is unclear to me why you do not want to do it this way. Instead, you seem to want to display the values of just one of those points (e.g. 9,9).
I don't think you will be able to do this directly in a call to geom_hex or stat_hexbin, as those functions are trying to faithfully represent all of the data. In fact, they are not necessarily expecting discrete coordinates like you have at all -- they work equally well on continuous data.
For your purpose, if you want finer control, you may want to instead use geom_tile and count the values yourself, eg. (using dplyr and magrittr):
countedData <-
dat %$%
table(x,y) %>%
as.data.frame()
ggplot(countedData
, aes(x = x
, y = y
, fill = Freq)) +
geom_tile()
and you might play with the representation a bit from there, but it would at least display each of the separate coordinates more faithfully.
Alternatively, you could filter your raw data to only include the points that are the maximum within a bin. That would require you to match the binning, but could at least be an option.
For completeness, here is how to adapt the stat_summary_hex solution that #Jon Nagra (OP) linked to. Note that there are a few additional steps, so I don't think that this is quite a duplicate. Specifically, the table step above is required to generate something that can be used as a z for the summaries, and then you need to convert x and y back from factors to the original scale.
ggplot(countedData
, aes(x = as.numeric(as.character(x))
, y = as.numeric(as.character(y))
, z = Freq)) +
stat_summary_hex(fun = max, bins = 10
, col = "white")
Of note, I still think that the geom_tile may be more useful, even it is not quite as flashy.

Making ordered heat maps in qplot (ggplot2)

I am making heat maps from correlations. I have two columns that represent ID's and a third column that gives the correlation between those two datapoints. I am struggling to get qplot to keep the order of my data in the file. Link to data:
https://www.dropbox.com/s/3l9p1od5vjt0p4d/SNPS.txt?n=7399684
Here is the code I am using to make the plot:
test <- qplot(x=x, y=y, data=PCIT, fill = col1, geom = "tile")
I have tried several order options but they don't seem to do the trick? Ideas?
Thanks and Happy Holidays
You need to set the levels of the factors x and y to be in the order you want them (as they come in from the file). Try
PCIT$x <- factor(PCIT$x, levels=unique(as.character(PCIT$x)))
and similarly with y.

Plotting multiple time-series in ggplot

I have a time-series dataset consisting of 10 variables.
I would like to create a time-series plot, where each 10 variable is plotted in different colors, over time, on the same graph. The values should be on the Y axis and the dates on the X axis.
Click Here for dataset csv
This is the (probably wrong) code I have been using:
c.o<-read.csv(file="co.csv",head=TRUE)
ggplot(c.o, aes(Year, a, b, c, d, e,f))+geom_line()
and here's what the output from the code looks like:
Can anyone point me in the right direction? I wasn't able to find anything in previous threads.
PROBLEM SOLVED, SEE BELOW.
One additional thing I would like to know:
Is it possible to add an extra line to the plot which represents the average of all variables across time, and have some smoothing below and above that line to represent individual variations?
If your data is called df something like this:
library(ggplot2)
library(reshape2)
meltdf <- melt(df,id="Year")
ggplot(meltdf,aes(x=Year,y=value,colour=variable,group=variable)) + geom_line()
So basically in my code when I use aes() im telling it the x-axis is Year, the y-axis is value and then the colour/grouping is by the variable.
The melt() function was to get your data in the format ggplot2 would like. One big column for year, etc.. which you then effectively split when you tell it to plot by separate lines for your variable.

Resources