-1

I would like to create a two-sided chart where the "target" variable is on the x axe,"birds" and "wolfs" are on the left-hand side of the y axe, each with its own proportions.

df<- read.table(text = "target birds    wolfs     
                              1     0.3      0.5 
                              0     0.9      0.2  ",header = TRUE)

I tried to follow the code in this link to suit my goal but with no success. How can I overcome this problem?

Update: attached is a sketch enter image description here

Community
  • 1
  • 1
mql4beginner
  • 2,193
  • 5
  • 34
  • 73
  • the link is not shown and can you give an example figure? – drmariod Feb 08 '17 at 09:57
  • 1
    Are you sure you want to have target on x axis which defines basically left and right, but also birds and wolf show left an right? – drmariod Feb 08 '17 at 10:00
  • Hello,@drmariod, link Attached. The idea is to show the success rate (values) of each variable in respect to the target 0/1 – mql4beginner Feb 08 '17 at 10:04
  • It is completely unclear to me what the two sides are, and how that would work with target being on the x-axis. Perhaps a little sketch would help us along. – Axeman Feb 08 '17 at 12:57
  • I believe that this is _intentionally_ not possible. See Hadley's comments at http://stackoverflow.com/a/3101876/4752675 – G5W Feb 08 '17 at 12:59
  • 1
    Hello @Axeman, I added a sketch.Hope it is clear now. – mql4beginner Feb 08 '17 at 13:17
  • _""birds" are on the left-hand side and "wolfs" is on the right-hand side"_, that's where the confusion came, since that is not what is in your picture. – Axeman Feb 08 '17 at 13:24

2 Answers2

2

You'll need a little reshaping for that, and ifelse to be a bit on the lazy side:

df2 <- tidyr::gather(df, 'var', 'val', -target)
ggplot(df2, aes(var)) +
  geom_col(aes(y = ifelse(target == 0, -val, val), fill = factor(target))) +
  coord_flip()

enter image description here

Axeman
  • 32,068
  • 8
  • 81
  • 94
  • Thank you @Axeman, I'm not sure I understand how to use it with my data, How can I use my data in your code, I don't see a placeholder for the "birds" and "wolfs"? – mql4beginner Feb 08 '17 at 13:30
  • 1
    @mql4beginner: Oops, I omitted a line of code, sorry. – Axeman Feb 08 '17 at 13:31
0
df<- read.table(text = "target birds    wolfs     
                              1     0.3      0.5 
                              0     0.9      0.2  ",header = TRUE)

df[df$target==0,] <- -df[df$target==0,]
df <- tidyr::gather(df,animal,value,c(birds,wolfs))

ggplot(df, aes(x = animal, y = value, fill = target)) + 
   geom_bar(stat = "identity") +
   coord_flip()

Try the above?

  • You'll want `target` as a factor though. And you can use `geom_col` instead of `geom_bar(stat = "identity")`. – Axeman Feb 08 '17 at 13:38