2014-05-04 14 views
7

Ho alcuni grafici creati con ggplot2 che vorrei incorporare in un'applicazione web: Mi piacerebbe migliorare le trame con i tooltip. Ho esaminato diverse opzioni. Attualmente sto sperimentando con la libreria rCharts e, tra gli altri, con i fossili grafici.R: grafici interattivi (tooltip): rCharts dimple plot: asse di formattazione

Ecco la ggplot originale:

enter image description here

Ecco un primo tentativo di trasporre questo per una trama fossetta:

enter image description here

Ho diversi problemi:

  1. dopo la formattazione l'asse y con le percentuali, i dati sono alterati.

  2. dopo aver formattato l'asse x per il rendering corretto delle date, vengono stampate troppe etichette.

Non sono legato ai grafici fossetta, quindi se ci sono altre opzioni che permettono un modo più semplice per modificare i formati degli assi Sarei felice di sapere. (? Classifiche Morris sembrano troppo bello, ma li tweaking sembra ancora più difficile, no)

Obiettivo: Fissare gli assi e aggiungere descrizioni comandi che danno sia la data (nel formato 1984) e il valore (nel formato 40%).

Se riesco a correggere 1 e 2, sarei molto felice. Ma ecco un'altra domanda, meno importante, nel caso qualcuno abbia dei suggerimenti:

Posso aggiungere le etichette di linea ("Top 10%") alle descrizioni dei comandi quando passano il mouse sulle linee?

Dopo aver scaricato i dati da: https://gist.github.com/ptoche/872a77b5363356ff5399, viene creato un frame di dati:

df <- read.csv("ps-income-shares.csv") 

La trama fossetta di base viene creato con:

library("rCharts") 
p <- dPlot(
    value ~ Year, 
    groups = c("Fractile"), 
    data = transform(df, Year = as.character(format(as.Date(Year), "%Y"))), 
    type = "line", 
    bounds = list(x = 50, y = 50, height = 300, width = 500) 
) 

Mentre base, finora tutto bene. Tuttavia, il seguente comando, destinati a convertire i dati y a percentuali, altera i dati:

p$yAxis(type = "addMeasureAxis", showPercent = TRUE) 

Che cosa sto facendo di sbagliato con showPercent?

Per riferimento, ecco il codice ggplot:

library("ggplot2") 
library("scales") 
p <- ggplot(data = df, aes(x = Year, y = value, color = Fractile)) 
p <- p + geom_line() 
p <- p + theme_bw() 
p <- p + scale_x_date(limits = as.Date(c("1911-01-01", "2023-01-01")), labels = date_format("%Y")) 
p <- p + scale_y_continuous(labels = percent) 
p <- p + theme(legend.position = "none") 
p <- p + geom_text(data = subset(df, Year == "2012-01-01"), aes(x = Year, label = Fractile, hjust = -0.2), size = 4) 
p <- p + xlab("") 
p <- p + ylab("") 
p <- p + ggtitle("U.S. top income shares (%)") 
p 

Per informazioni, il grafico sopra si basa sui dati messi insieme da Thomas Piketty e Emmanuel Saez nel loro studio di top redditi . I dati e altro possono essere trovati sul loro sito web, ad es.

http://elsa.berkeley.edu/users/saez/

http://piketty.pse.ens.fr/en/

EDIT:

Ecco uno screenshot della soluzione di Ramnath, con un titolo aggiunto e le etichette degli assi ottimizzato. Grazie Ramnath!

p$xAxis(inputFormat = '%Y-%m-%d', outputFormat = '%Y') 
p$yAxis(outputFormat = "%") 
p$setTemplate(afterScript = " 
    <script> 
    myChart.axes[0].timeField = 'Year' 
    myChart.axes[0].timePeriod = d3.time.years 
    myChart.axes[0].timeInterval = 10 
    myChart.draw() 
    myChart.axes[0].titleShape.remove() // remove x label 
    myChart.axes[1].titleShape.remove() // remove y label 
    myChart.svg.append('text')   // chart title 
     .attr('x', 40) 
     .attr('y', 20) 
     .text('U.S. top income shares (%)') 
     .style('text-anchor','beginning') 
     .style('font-size', '100%') 
     .style('font-family','sans-serif') 
    </script>    
") 
p 

enter image description here

Per cambiare (piuttosto che rimuovere) le etichette degli assi, per esempio:

myChart.axes[1].titleShape.text('Year') 

Per aggiungere una leggenda del terreno:

p$set(width = 1000, height = 600) 
p$legend(
    x = 580, 
    y = 0, 
    width = 50, 
    height = 200, 
    horizontalAlign = "left" 
) 

Per salvare il rchart:

p$save("ps-us-top-income-shares.html", cdn = TRUE) 

Un'alternativa basato sulla libreria nvd3 può essere ottenuto (senza che nessuna delle cose fantasiose) con:

df$Year <- strftime(df$Year, format = "%Y") 
n <- nPlot(data = df, value ~ Year, group = 'Fractile', type = 'lineChart') 

risposta

6

Ecco un modo per risolvere (1) e (2). L'argomento showPercent non deve aggiungere% ai valori, ma per ricalcolare i valori in modo che vengano impilati fino al 100%, motivo per cui viene visualizzato il comportamento segnalato.

A questo punto, vedrete che dobbiamo ancora scrivere javascript personalizzati per modificare l'asse x per farlo visualizzare nel modo in cui lo vogliamo. Nelle prossime iterazioni, ci sforzeremo di consentire l'intera API dimple essere accessibile all'interno di rCharts.

df <- read.csv("ps-income-shares.csv") 
p <- dPlot(
    value ~ Year, 
    groups = c("Fractile"), 
    data = df, 
    type = "line", 
    bounds = list(x = 50, y = 50, height = 300, width = 500) 
) 
p$xAxis(inputFormat = '%Y-%m-%d', outputFormat = '%Y') 
p$yAxis(outputFormat = "%") 
p$setTemplate(afterScript = " 
    <script> 
    myChart.axes[0].timeField = 'Year' 
    myChart.axes[0].timePeriod = d3.time.years 
    myChart.axes[0].timeInterval = 5 
    myChart.draw() 

    //if we wanted to change our line width to match the ggplot chart 
    myChart.series[0].shapes.style('stroke-width',1); 

    </script> 
") 
p 
+0

avevo bisogno di aggiornarmi con 'devtools :: install_github ("rCharts", "ramnathv", ref = "dev")', eccellente e grazie Ramnath! – PatrickT

+0

Ah. Immaginavo che lo avessi già fatto da quando stavi usando 'afterScript'. – Ramnath

+0

Beh, sì, ma per qualche motivo ha bisogno di un aggiornamento ;-) – PatrickT

4

rCharts è in rapida evoluzione. So che è tardi, ma nel caso che qualcun altro vorrebbe vederlo, ecco una replica quasi completa del campione ggplot mostrato.

#For information, the chart above is based 
    #on the data put together by Thomas Piketty and Emmanuel Saez 
    #in their study of U.S. top incomes. 
    #The data and more may be found on their website, e.g. 
    #http://elsa.berkeley.edu/users/saez/ 
    #http://piketty.pse.ens.fr/en/ 

    #read in the data 
    df <- read.csv(
    "https://gist.githubusercontent.com/ptoche/872a77b5363356ff5399/raw/ac86ca43931baa7cd2e17719025c8cde1c278fc1/ps-income-shares.csv", 
    stringsAsFactors = F 
) 

    #get year as date 
    df$YearDate <- as.Date(df$Year) 

    library("ggplot2") 
    library("scales") 
    p <- ggplot(data = df, aes(x = YearDate, y = value, color = Fractile)) 
    p <- p + geom_line() 
    p <- p + theme_bw() 
    p <- p + scale_x_date(limits = as.Date(c("1911-01-01", "2023-01-01")), labels = date_format("%Y")) 
    p <- p + scale_y_continuous(labels = percent) 
    p <- p + theme(legend.position = "none") 
    p <- p + geom_text(data = subset(df, Year == "2012-01-01"), aes(x = YearDate, label = Fractile, hjust = -0.2), size = 4) 
    p <- p + xlab("") 
    p <- p + ylab("") 
    p <- p + ggtitle("U.S. top income shares (%)") 
    gp <- p 
    gp 


    p <- dPlot(
    value ~ Year, 
    groups = c("Fractile"), 
    data = df, 
    type = "line", 
    bounds = list(x = 50, y = 50, height = 300, width = 500) 
) 
    p$xAxis(inputFormat = '%Y-%m-%d', outputFormat = '%Y') 
    p$yAxis(outputFormat = "%") 
    p$setTemplate(afterScript = " 
    <script> 
     myChart.axes[0].timeField = 'Year' 
     myChart.axes[0].timePeriod = d3.time.years 
     myChart.axes[0].timeInterval = 5 
     myChart.draw() 

     //if we wanted to change our line width to match the ggplot chart 
     myChart.series[0].shapes.style('stroke-width',1); 

     //to take even one step further 
     //we can add labels like in the ggplot example 
     myChart.svg.append('g') 
     .selectAll('text') 
     .data(
      d3.nest().key(function(d){return d.cx}).map(myChart.series[0]._positionData)[myChart.axes[0]._max]) 
     .enter() 
      .append('text') 
      .text(function(d){return d.aggField[0]}) 
      .attr('x',function(d){return myChart.axes[0]._scale(d.cx)}) 
      .attr('y',function(d){return myChart.axes[1]._scale(d.cy)}) 
      .attr('dy','0.5em') 
      .style('font-size','80%') 
      .style('fill',function(d){return myChart._assignedColors[d.aggField[0]].fill}) 
    </script> 
    ") 
    p$defaultColors(ggplot_build(gp)$data[[2]]$colour) 
    p 
+0

a seconda del ramo/versione di 'rCharts' che stai usando, questo potrebbe o potrebbe non funzionare. Hai 'devtools :: install_github' in un po '? Se è così, probabilmente non funzionerà. Cercherò di aggiornare – timelyportfolio

+0

deve essere stato un problema locale, perché oggi sono in grado di riprodurre la trama con il codice che hai postato. Ho cancellato i miei commenti. Grazie! – PatrickT

+1

Il tuo link git non sembra funzionare. Mi chiedo se hai migrato i tuoi file da qualche altra parte perché lo stesso è accaduto per le incredibili serie temporali dei prezzi delle case basate sul grafico NYT che hai fatto. Tuttavia, ho scaricato i dati di Patrick e ha funzionato perfettamente.E 'stato estremamente utile, grazie. –