Кто-нибудь знает, как сделать такую ​​диаграмму с помощью ggplot2 в R? - PullRequest
1 голос
/ 25 мая 2020

См. Изображение того, что я пытаюсь создать с помощью ggplot2 в R. На изображении показаны мои образцы данных и то, как я хочу, чтобы диаграмма выглядела и функционировала. Есть идеи?

enter image description here

Ответы [ 3 ]

2 голосов
/ 25 мая 2020

Вот точное воспроизведение: enter image description here


df <- data.frame( Ticker = c('FB','AAPL','GOOG'), 
                  Name = c('Facebook','Apple','Google'), 
                  Purchase = c(16,5,21), 
                  Current = c(45,2,32), 
                  Target = c(42,22,42), 
                  Action = c('Sell','Buy','Hold') )

df$Ticker <- factor(df$Ticker, levels = as.character(df$Ticker))
df$Action <- factor(df$Action, levels = as.character(df$Action))

ggplot(df, aes(Ticker, Current)) + 
  geom_boxplot(aes(ymin = Purchase, middle = Purchase, lower = Purchase,
                   upper = Target, ymax = Target, fill = Action),
               stat = "identity", size = 0) + 
  scale_fill_manual(values = c("#EE8800", "#6688FF", "#EEDD00"), guide = FALSE) +
  scale_y_continuous(labels = function(x) paste0("$", x)) +
  geom_point(size = 10) +
  geom_point(size = 9, colour = "forestgreen") +
  scale_x_discrete() +
  theme_bw() +
  theme(panel.grid = element_blank(),
        panel.border  = element_rect(size=2),
        axis.title = element_blank(),
        text = element_text(size = 16),
        plot.margin = margin(50, 20, 20, 20)) +
  coord_cartesian(clip = "off", ylim = c(0, 45)) +
  geom_text(aes(y = 50, label = Action), size = 5)
2 голосов
/ 25 мая 2020

Вот моя попытка:

#sample data
library( data.table )
DT <- data.table::fread("Ticker Name Purchase Current Target Action
FB   Facebook 16 45 42 Sell
AAPL Apple     5  2 22 Buy
GOOG Google   21 32 42 Hold")

вот мы go ...

#add rownumbers
DT[, rownum := .I ]
#make ticker a factor to avoid reordering
DT[, Ticker_f := factor(Ticker, levels = Ticker) ]
#determine maximum y-value
max_y_value = 10 * ceiling( max( matrixStats::colMaxs( as.matrix( DT[, .(Purchase, Current, Target ) ] ) ) ) / 10 )

#build chart
library( ggplot2 )
library( scales )
#plot using Name as fill-color, and Ticker for x-axis labels
ggplot( data = DT, aes( x = Ticker_f, fill = Name ) ) +
  #create the rectangles
  geom_rect( aes( ymin = Purchase, ymax = Target ), xmin = DT$rownum - 0.2, xmax = DT$rownum + 0.2, color = "black" ) + 
  #draw points
  geom_point( aes( y = Current ), colour = "purple", size = 8 ) + 
  #show action on top
  geom_text( aes( y = max_y_value, label = Action ) ) + 
  #set labels lfor y-axis
  scale_y_continuous( labels = scales::label_dollar() ) + 
  #set theme
  theme_classic() + 
  #zoom to relevant values
  coord_cartesian( ylim = c(0, max_y_value ) ) + 
  #remove legend
  theme( legend.position = "none" ) +
  #set axis labels
  labs( x = "", y = "" )

enter image description here

0 голосов
/ 25 мая 2020

Спасибо @AllanCameron и @Wimpel за ваш вклад. В итоге я смешал оба ваших ответа, чтобы они соответствовали тому, что я искал. Ниже показано, что было реализовано в KNIME с использованием узла R View (Table).

library(data.table)
DT <- data.table::setDT(knime.in)

#add rownumbers
DT[, rownum := .I ]
#make ticker a factor to avoid reordering
DT[, Ticker_f := factor(Ticker, levels = Ticker) ]
#determine maximum y-value
max_y_value = 10 * ceiling( max( matrixStats::colMaxs( as.matrix( DT[, .(Purchase, 
Current, Target ) ] ) ) ) / 10 )

#build chart
library( ggplot2 )
library( scales )
#plot using Name as fill-color, and Ticker for x-axis labels
plot3 <- ggplot( data = DT, aes( x = Ticker_f, fill = Ticker ) ) +
  #create the rectangles
  geom_rect( aes( ymin = Purchase, ymax = Target ), xmin = DT$rownum - 0.2, xmax = 
DT$rownum + 0.2, color = "black" ) + 
  #set colors
  scale_fill_manual(values = c("#737373", "#4472C4", "#ED7D31", "#FFC000"), guide 
= FALSE) +
  #draw points
  geom_point( aes( y = Current ), colour = "#70AD47", size = 10 ) + 
  #show action on top
  geom_text( aes( y = max_y_value, label = Action ), size = 5 ) + 
  #set labels lfor y-axis
  scale_y_continuous( labels = scales::label_dollar() ) + 
  #set theme
  theme_classic() + 
  #zoom to relevant values
  coord_cartesian( ylim = c(0, max_y_value ) ) + 
  #
  ggtitle("Current Status of Portfolio") +
  xlab("Tickers") + 
  ylab("Price") +
  theme(
    plot.title = element_text(color="gray", size=14, face="bold.italic"),
    axis.title.x = element_text(color="gray", size=14, face="bold"),
    axis.title.y = element_text(color="gray", size=14, face="bold"),
    axis.text.x = element_text(size = 14),
    axis.text.y = element_text(size = 14))


plot(plot3)
...