1

I have created a tile plot, as below: enter image description here

I'd like to rename the y axis ticks, instead of 1 - to "country", 2- to "city", 3 - to "all". I couldn't find a way to do it. I have the following script:

ggplot(test_df, aes(num, sample_type, fill = exist)) + 
geom_tile(width=0.9, height=0.9,color = "gray")+ 
scale_fill_gradientn(colours = c("white", "lightgreen"), values = c(0,1))+ 
theme(axis.text.x = element_text(angle = 90, hjust = 1), 
legend.position="none")+
scale_x_discrete(position = "top") + labs(x = "", y= "Sample Type")

How can I do that without changing my dataframe?

Here is a sample of my dataframe:

test_df <- data.frame(
num = c("num1","num1","num1","num2","num2","num2","num3","num3","num3"),
sample_type = c(1,2,3,1,3,2,3,1,2),
exist = c(1,0,0,1,1,0,1,0,0))
Bella
  • 937
  • 1
  • 13
  • 25
  • 1
    Please provide sample data – Felipe Flores Jul 26 '18 at 20:30
  • 2
    When asking for help, you should include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. But you can look at `scale_y_discrete(labels=)` for a start. – MrFlick Jul 26 '18 at 20:30
  • Adding to @MrFlick's comment, you can try a named vector like `scale_y_discrete(labels=c(1 = "country", 2 = "city", 3 = "all"))` – Felipe Flores Jul 26 '18 at 20:31
  • You mean to give you a sample of my dataframe? – Bella Jul 26 '18 at 20:40
  • On a general note, it's nice to present your code in a more readable format. – BroVic Jul 26 '18 at 20:48
  • I edited the question with a sample of my dataframe. @FelipeFlores Thanks, but it didn't work... – Bella Jul 26 '18 at 20:56
  • You are right...fixed it – Bella Jul 26 '18 at 21:08
  • small comment on your plot : in `labs()`, would rather specify `x=NULL`, because otherwise you are actually plotting 'something'. For the question, you would not need your `theme()` call, nor your `scale_color_gradient()`, nor the arguments in `geom_tile`. all those things make your questions a bit convoluted. for the next time :) – tjebo Jul 26 '18 at 21:18

1 Answers1

5

It looks like you want to treat your Y values as discreate values, rather than numeric. The easiest way to deal with that is to make the number a factor. You can do

ggplot(test_df, aes(num, factor(sample_type), fill = exist)) + 
  geom_tile(width=0.9, height=0.9,color = "gray")+ 
  scale_fill_gradientn(colours = c("white", "lightgreen"), values = c(0,1))+ 
  theme(axis.text.x = element_text(angle = 90, hjust = 1), 
        legend.position="none")+
  scale_y_discrete(labels=c("1"="country","2"="city", "3"="all")) +
  scale_x_discrete(position = "top") + labs(x = "", y= "Sample Type")

Notice the aes(num, factor(sample_type), ...) to convert sample_type to a factor and then the scale_y_discrete to control the labels for those levels.

MrFlick
  • 195,160
  • 17
  • 277
  • 295