Question

I have the following data frame:

test <- data.frame(x=c(1:8), y=c(8:1), Type=c("A","A","A","A","B","B","B","B"), Condition=c("aa","bb","cc","dd"))

  x y Type Condition
1 1 8    A        aa
2 2 7    A        bb
3 3 6    A        cc
4 4 5    A        dd
5 5 4    B        aa
6 6 3    B        bb
7 7 2    B        cc
8 8 1    B        dd

When I run following command, I can get correct graphs like "test1".

q <- ggplot(test, aes(x, y, color=Type)) + geom_point(size=10) + labs(title = "test1")
q <- q + facet_wrap("Condition")
q

test1: test1

But actually I want to run the following command, because colnames of dataset I analyse are sometimes different.

q <- ggplot(test, aes(test[,1], test[,2], color=Type)) + geom_point(size=10) + labs(title = "test2")
q <- q + facet_wrap("Condition")
q

But the output is wrong like "test2": test2

Could someone please tell me a solution? Thanks for your help!


Edit This issue was solved by using aes_string() like this.

p <- ggplot(test, aes_string(x = colnames(test)[1], y = colnames(test)[2], color="Type")) + geom_point(size=10)
p <- p + facet_wrap("Condition")
p

Thank you all!

Was it helpful?

Solution

ggplot doesn't like column indexing inside of aes. Use aes_string() instead with indexed column names:

ggplot(data=test,
       mapping=aes_string(x=names(test)[1], y=names(test)[2], color="Type")) + 
       geom_point(size=10) +
       facet_wrap(~ Condition)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top