I have a scatterplot that breaks the points out into different colors by the category. I want one of these categories to have a line connecting the dots to highlight this category's data. I'm having trouble figuring this out...
Round <- read.csv("http://goo.gl/3c3vBU") # Data
qplot(factor(Round), Opp.Landed, data=floyd, color=Opponent, size=Opp.Percent.Landed, alpha = I(0.7)) +
labs(x="Round", y="Punches Landed", title="Opponent Punches Landed / Percentage", colour="Boxer", size="Connect Percentage") +
scale_linetype_manual(values=1:2, labels=c("Boxer", "Connect Percentage")) +
guides(colour = guide_legend(override.aes = list(size=5)))
The ftheme code is just colors and formatting. Any ideas? I've tried adding geom_line(aes(linetype=floyd[Opponent="Manny Pacquiao"]), size=1) but it errors out with
Error in [.data.frame`(floyd, Opponent = "Manny Pacquiao") : unused argument (Opponent = "Manny Pacquiao")
EDIT: I've updated the code above to exclude ftheme so it's reproducable. Please see the sample dataset from with three categories. I just want any one of these to have connected points: http://goo.gl/3c3vBU
I can't give a tailored answer without being able to run your code on a sample of your data, but you can use scale_color_manual to set the colour of the category you want to highlight to, say, "red" and set all the others to NA. For example, if the category you want to highlight is the second category and you have a total of five categories, then add this to your plot code:
scale_colour_manual(values=c(NA, "red", rep(NA,3)))
If you have points that are tied to the color aesthetic as well, then you'll need to change the points to a fill aesthetic (e.g., fill=Opponent) and use a filled point marker that you can set manually using shape or pch. Otherwise, your point markers will disappear along with the lines. Marker numbers 21 through 25 are filled (see ?pch for more on point markers).
UPDATE: Here's my attempt using the data you provided. I'm not exactly sure how you want the legends and other details to look, so let me know if this works. I've switched to ggplot, as I don't know the ins and outs of qplot.
ggplot(floyd, aes(factor(Round), Opp.Landed, color=Opponent,
fill=Opponent, group=Opponent, size=Opp.Percent.Landed),
alpha = 0.7, pch=21) +
geom_point(pch=21, colour=NA) +
geom_line() +
labs(x="Round", y="Punches Landed", title="Opponent Punches Landed / Percentage",
colour="Boxer", size="Connect Percentage") +
scale_linetype_manual(values=1:2, labels=c("Boxer", "Connect Percentage")) +
scale_colour_manual(values=c(hcl(15,100,65), NA, NA), guide="none") +
guides(fill = guide_legend(override.aes = list(size=5)))
Try to add:
geom_line(data=subset(floyd,Opponent=="Manny Pacquiao"), aes(factor(Round), Opp.Landed, group=Opponent), size = 2)
Very easy piece of code which makes a subset of your data of which gives a nice line of size 2 through your data points.
(for the image I used the opponent Miguel Cotto since you did not provide Manny Pacquiao in the data set)
Related
Hello I Have a plot showing a PCA reuslt, the issue is that I want to show how the points behave in the plot accoriding to two variables, let's say sample date and depth of sampling:
I use autoplot for this porpuse:
autoplot(PCA_results, data = data1, colour = 'sample_date' ,
shape = 'depth_m', main = "PCA for samples") + scale_shape_identity()
I had to use scale_shape_identity() due to the fact that the "depth_m" variable have two continuous values (5 meters and 20 meters) and was not acepted without scale_shape_identity()
the resulting plot is the following one:
So in addition to showing sample_date variable in the legend I want to display the depth one too, how can I do this ?
The description of the help menu of scale_shape_identity() appoints that "These scales will not produce a legend unless you also supply the breaks, labels, and type of guide you want." But I'm not sure how to provide the labels, breaks and type of guide.
I have used the following code to generate a plot with ggplot:
I want the legend to show the runs 1-8 and only the volumes 12.5 and 25 why doesn't it show it?
And is it possible to show all the points in the plot even though there is an overlap? Because right now the plot only shows 4 of 8 points due to overlap.
OP. You've already been given a part of your answer. Here's a solution given your additional comment and some explanation.
For reference, you were looking to:
Change a continuous variable to a discrete/discontinuous one and have that reflected in the legend.
Show runs 1-8 labeled in the legend
Disconnect lines based on some criteria in your dataset.
First, I'm representing your data here again in a way that is reproducible (and takes away the extra characters so you can follow along directly with all the code):
library(ggplot2)
mydata <- data.frame(
`Run`=c(1:8),
"Time"=c(834, 834, 584, 584, 1184, 1184, 938, 938),
`Area`=c(55.308, 55.308, 79.847, 79.847, 81.236, 81.236, 96.842, 96.842),
`Volume`=c(12.5, 12.5, 12.5, 12.5, 25.0, 25.0, 25.0, 25.0)
)
Changing to a Discrete Variable
If you check the variable type for each column (type str(mydata)), you'll see that mydata$Run is an int and the rest of the columns are num. Each column is understood to be a number, which is treated as if it were a continuous variable. When it comes time to plot the data, ggplot2 understands this to mean that since it is reasonable that values can exist between these (they are continuous), any representation in the form of a legend should be able to show that. For this reason, you get a continuous color scale instead of a discrete one.
To force ggplot2 to give you a discrete scale, you must make your data discrete and indicate it is a factor. You can either set your variable as a factor before plotting (ex: mydata$Run <- as.factor(mydata$Run), or use code inline, referring to aes(size = factor(Run),... instead of just aes(size = Run,....
Using reference to factor(Run) inline in your ggplot calls has the effect of changing the name of the variable to be "factor(Run)" in your legend, so you will have to also add that to the labs() object call. In the end, the plot code looks like this:
ggplot(data = mydata, aes(x=Area, y=Time)) +
geom_point(aes(color =as.factor(Volume), size = Run)) +
geom_line() +
labs(
x = "Area", y = "Time",
# This has to be changed now
color='Volume'
) +
theme_bw()
Note in the above code I am also not referring to mydata$Run, but just Run. It is greatly preferable that you refer to just the name of the column when using ggplot2. It works either way, but much better in practice.
Disconnect Lines
The reason your lines are connected throughout the data is because there's no information given to the geom_line() object other than the aesthetics of x= and y=. If you want to have separate lines, much like having separate colors or shapes of points, you need to supply an aesthetic to use as a basis for that. Since the two lines are different based on the variable Volume in your dataset, you want to use that... but keep the same color for both. For this, we use the group= aesthetic. It tells ggplot2 we want to draw a line for each piece of data that is grouped by that aesthetic.
ggplot(data = mydata, aes(x=Area, y=Time)) +
geom_point(aes(color =as.factor(Volume), size = Run)) +
geom_line(aes(group=as.factor(Volume))) +
labs(
x = "Area", y = "Time", color='Volume'
) +
theme_bw()
Show Runs 1-8 Labeled in Legend
Here I'm reading a bit into what you exactly wanted to do in terms of "showing runs 1-8" in the legend. This could mean one of two things, and I'll assume you want both and show you how to do both.
Listing and showing sizes 1-8 in the legend.
To set the values you see in the scale (legend) for size, you can refer to the various scale_ functions for all types of aesthetics. In this case, recall that since mydata$Run is an int, it is treated as a continuous scale. ggplot2 doesn't know how to draw a continuous scale for size, so the legend itself shows discrete sizes of points. This means we don't need to change Run to a factor, but what we do need is to indicate specifically we want to show in the legend all breaks in the sequence from 1 to 8. You can do this using scale_size_continuous(breaks=...).
ggplot(data = mydata, aes(x=Area, y=Time)) +
geom_point(aes(color =as.factor(Volume), size = Run)) +
geom_line(aes(group=as.factor(Volume))) +
labs(
x = "Area", y = "Time", color='Volume'
) +
scale_size_continuous(breaks=c(1:8)) +
theme_bw()
Showing all of your runs as points.
The note about showing all runs might also mean you want to literally see each run represented as a discrete point in your plot. For this... well, they already are! ggplot2 is plotting each of your points from your data into the chart. Since some points share the same values of x= and y=, you are getting overplotting - the points are drawn over top of one another.
If you want to visually see each point represented here, one option could be to use geom_jitter() instead of geom_point(). It's not really great here, because it will look like your data has different x and y values, but it is an option if this is what you want to do. Note in the code below I'm also changing the shape of the point to be a hollow circle for better clarity, where the color= is the line around each point (here it's black), and the fill= aesthetic is instead used for Volume. You should get the idea though.
set.seed(1234) # using the same randomization seed ensures you have the same jitter
ggplot(data = mydata, aes(x=Area, y=Time)) +
geom_jitter(aes(fill =as.factor(Volume), size = Run), shape=21, color='black') +
geom_line(aes(group=as.factor(Volume))) +
labs(
x = "Area", y = "Time", fill='Volume'
) +
scale_size_continuous(breaks=c(1:8)) +
theme_bw()
I have an ethogram-like ggplot where I plot the value of a factor quadrant (1 to 4), which is plotted for each frame of a movie (frameID). The color is given by 3 animals that are being tracked.
I am fairly satisfied with the graph but the amount of points makes it difficult to see, even with alpha. I was wondering how to add position_dodge in a way that doesn't destroy the plot.
ggplot(dataframe) ,
aes(frameID, quadrant, color=animal)) +
geom_jitter(alpha=0.5) +
scale_color_manual(values = c("#1334C1","#84F619", "#F43900")) +
theme_classic()+
theme(legend.position = 'none')
This link has useful info about dodging using geom_point.
R: How to spread (jitter) points with respect to the x axis?
I can change to geom_point with height, which works but it produces something awful.
+ geom_point(position = position_jitter(w = 0, h = 2))
Update
Data lives in GitHub
Lowering the alpha or changing size helps, adds trouble when rescaling the image.
https://github.com/matiasandina/MLA2_Tracking/blob/master/demo_data/sample_data.csv
Update 2022
It's been a while since I posted this initially, my original thoughts changed and are better reflected here, but I am still looking for a ggplot2 version of doing this!
I am a newbie to R and hence having some problems in plotting using ggplot and hence need help.
In the above diagram, if any of my bars have high values (in this case, a green one with value of 447), the plot and the plot title gets overlapped. The values here are normalised / scaled such that the y-axis values are always between 0-100, though the label might indicate a different number (this is the actual count of occurrences, where as the scaling is done based on percentages).
I would like to know how to avoid the overlap of the plot with the plot title, in all cases, where the bar heights are very close to 100.
The ggplot function I am using is as below.
my_plot<-ggplot(data_frame,
aes(x=as.factor(X_VAR),y=GROUP_VALUE,fill=GROUP_VAR)) +
geom_bar(stat="identity",position="dodge") +
geom_text(aes(label = BAR_COUNT, y=GROUP_VALUE, ymax=GROUP_VALUE, vjust = -1), position=position_dodge(width=1), size = 4) +
theme(axis.text.y=element_blank(),axis.text.x=element_text(size=12),legend.position = "right",legend.title=element_blank()) + ylab("Y-axis label") +
scale_fill_discrete(breaks=c("GRP_PERCENTAGE", "NORMALIZED_COUNT"),
labels=c("Percentage", "Count of Jobs")) +
ggtitle("Distribution based on Text Analysis 2nd Level Sub-Category") +
theme(plot.title = element_text(lineheight=1, face="bold"))
Here is the ggsave command, in case if that is creating the problem, with dpi, height and width values.
ggsave(my_plot,file=paste(paste(variable_name,"my_plot",sep="_"),".png",sep = ""),dpi=72, height=6.75,width=9)
Can anyone please suggest what need to be done to get this right?
Many Thanks
As Axeman suggests ylim is useful Have a look at the documentation here:
http://docs.ggplot2.org/0.9.3/xylim.html
In your code:
my_plot + ylim(0,110)
Also, I find this intro to axis quite useful:
http://www.cookbook-r.com/Graphs/Axes_(ggplot2)/
Good luck!
I know I'm not the first to ask a question in this arena but I haven't been able to figure out the solution to my particular quandary. Here's a stripped-down example of my problem.
data<-data.frame(Est=c(1:20,1:20),Measured=c(1:5,5:9,1:6,3:6,1:6,3:6,1:4,4,4:8),variable=c(rep("Plot1",20),rep("Plot2",20)))
p<-ggplot(data,aes(y=Est,x=Measured,shape=variable))
p<- p + geom_point(stat="identity") +coord_fixed(xlim=c(0,25),ylim=c(0,25)) + theme_bw()
p #If you plot the figure at this point, the points stand alone in the legend
p<-p+ geom_abline(intercept=0,slope=1,aes(linetype="1:1",color="1:1"),show_guide=TRUE)
p # Once the geom_abline is added, there are lines through the points. :(
p<-p+scale_color_manual(name="Lines",
values=c("1:1"="black"))
p<- p + scale_linetype_manual(name="Lines",
values=c("1:1"=2))
p<-p + scale_shape_manual(values=c(0,20), name = "")
p<- p+xlab(expression(paste("Measured volume(",ducks^{3},"",ha^{-1},")",sep="")))
p<-p+ ylab(expression(paste("Estimated volume (",ducks^{3},"",ha^{-1},")",sep="")))
As you can see, the legend for the points includes slashes (which I think are actually a line), and I would really prefer that the points were alone.
While the example code has only 1 line and linetype, the actual figure I've made includes five different lines of varying colors and linetypes, and thus I need a solution that allows me to include multiple geom_abline calls with color and linetype specified.
And no, I'm not really measuring the volume of anything in ducks, although that would be really entertaining to study...
Override the aesthetic mapping:
p + guides(shape = guide_legend(override.aes = list(linetype = 0)))
I always end up trying to override aesthetics by setting them to NULL, but for some reason that intuition is usually wrong.