Please find my code below (I did not place the updated code for each image here.) The Code below is for the image labeled original :
packages <- c("ggplot2", "dplyr", "quantreg", "officer","tidyverse","here","glue","rvg","viridis","scales")
install.packages(setdiff(packages, rownames(installed.packages())))
lapply(packages, require, character.only = TRUE)
data <- read.csv(file='Spiderplot_data.csv', header=TRUE)
Progressed <- as.factor(data$Progression)
Response <- as.factor(data$X)
Response <- factor(data$X, levels = c("Progressive Disease", "Stable Disease", "Partial Response", "Complete Response"))
highlight_df <- filter(data, Progression == 1)
p <- ggplot() +
geom_line(
data,
mapping = aes(
x = Cycle,
y = Change,
group = Study_ID,
color = Response
)
) +
geom_point(
data,
mapping = aes(
x = Cycle,
y = Change,
group = Study_ID,
color = Response,
shape = Progressed
)
) +
geom_point( # Data set with just points
highlight_df,
shape = 18,
size = 2.8,
mapping = aes(
x = Cycle,
y = Change,
group = Study_ID,
)
) +
scale_shape_manual(
values = c(16,18)
) +
scale_color_brewer(
palette = "Set1"
) +
scale_x_continuous(
name = "Cycle",
breaks = c(0,2,4,6,8,10,12,14,16,18,20,30,40,45),
limits = c(0,45),
expand = expansion(mult = c(0,0.001))
) +
scale_y_continuous(
name = "Percent Change in Lesion SLD (%)",
breaks = c(-1,-.75,-.50,-.40,-.30,-.20,-.10,.10,.20,.30,.40,.50,.65),
limits = c(-1,.65),
labels = percent
) +
ggtitle("Response Plot")
p
p_dml <- rvg::dml(ggobj = p)
# initialize PowerPoint slide ----
officer::read_pptx() %>%
# add slide ----
officer::add_slide() %>%
# specify object and location of object ----
officer::ph_with(p_dml, ph_location(width = 10, height = 5)) %>%
# export slide -----
base::print(
target = here::here(
"demo_3.pptx"
)
)
As you can see the distance between each point on the x axis is linear and equal, is there a way to spread out the distance on the plot between 0-20 and make space between 20-40 smaller?
As you can see I have tried to do this using the expand function, but to no avail, I am using the funciton wrong?
Any help would be much appreciated.
Orginal image
Image with scale_x_sqrt
Image with scale_x_continuous(trans = scales::pseudo_log_trans(sigma = 3))
While this is as close as we've gotten to what I am looking for, is there a function that allows me to customize exactly where the ticks are on the axis?
Related
Background: I want to make a Shiny app that colleagues, who don't use R and don't have it installed, can upload .csv files to, and then download a report generated by the app, using their web browser. The report will be an editable word file which will include graphs plotted for each different group in the dataset provided (denoted by an identifier in a particular column).
Colleagues will upload one or more .csv files which will contain multiple datasets with the same column headings. These will ideally get combined into a single dataframe using rbind or similar.
The Shiny app will then initialise the RMarkdown report, which will identify all the distinct identifiers in a particular column, which I want to use in a purrr/map command to filter the dataset by each identifier, and plot a graph in ggplot for each. There should also be a title above each graph, and a sentence of text below each graph, which will also need to be produced by iterative functions.
I've put what I have so far below (and have tried various other permutations and commands along the way). I managed to get something like the below function to plot only the graphs, but want to amend it so that three functions (write header, plot graph, write sentence) are executed at once for each item in the list before the script moves to the next item, and am struggling with this. I also couldn't get that function to work with the annotate and xlim commands at the end of the ggplot sequence, but it would be really helpful if those worked, too.
Any help or advice would be greatly appreciated. Thank you so much.
plot <- function(x) {
report.data %>%
filter(identifier == .data[[.x]]) %>%
ggplot(aes(x = sample.no, y = result)) +
geom_point(aes(colour = analyser)) +
geom_hline(aes(yintercept = mean(result) + 2 * sd(result)), colour = "red", linetype = "dashed") +
geom_hline(aes(yintercept = mean(result) - 2 * sd(result)), colour = "red", linetype = "dashed") +
xlab("Sample number") +
ylab("Result") +
theme_classic() #+
#annotate("text", x = max(sample.no) + 2, y = mean(result), size = 3.5) +
#xlim(0, max(sample.no) + 2)
}
funs <- c(
header,
plot,
text
)
args <- list(unique(report.data$identifier))
report.data %>% map_df(~funs %>% map(exec, .x, !!!args))
Code to generate example input data:
library(dplyr)
set.seed(1234)
test1.level1.analyser1 <- data.frame(
result = rnorm(25, mean = 2.5, sd = 0.2),
test = c("test1"),
level = c("level1"),
sample.no = c(1:25),
analyser = c("analyser1")
)
test1.level1.analyser2 <- data.frame(
result = rnorm(25, mean = 2.6, sd = 0.1),
test = c("test1"),
level = c("level1"),
sample.no = c(1:25),
analyser = c("analyser2")
)
test1 <- rbind(test1.level1.analyser1, test1.level1.analyser2)
test2.level1.analyser1 <- data.frame(
result = rnorm(25, mean = 10, sd = 2),
test = c("test2"),
level = c("level1"),
sample.no = c(1:25),
analyser = c("analyser1")
)
test2.level1.analyser2 <- data.frame(
result = rnorm(25, mean = 9.5, sd = 0.75),
test = c("test2"),
level = c("level1"),
sample.no = c(1:25),
analyser = c("analyser2"))
test2.level2.analyser1 <- data.frame(
result = rnorm(25, mean = 30, sd = 1.8),
test = c("test2"),
level = c("level2"),
sample.no = c(1:25),
analyser = c("analyser1")
)
test2.level2.analyser2 <- data.frame(
result = rnorm(25, mean = 9.5, sd = 0.75),
test = c("test2"),
level = c("level2"),
sample.no = c(1:25),
analyser = c("analyser2"))
test2.level1 <- rbind(test2.level1.analyser1, test2.level1.analyser2)
test2 <- rbind(test2.level1.analyser1, test2.level1.analyser2, test2.level2.analyser1, test2.level2.analyser2)
input.data <- rbind(test1, test2) %>% mutate(identifier = paste(test, level, sep = " "))
Would it be an option to integrate the individual titles above and sentences below the graph directly into ggplot? In that case I would suggest to modify the plot function like this:
library(ggplot2)
library(dplyr)
library(purrr)
my_plot <- function(df) {
ggplot(df, aes(x = sample.no, y = result)) +
geom_point(aes(colour = analyser)) +
geom_hline(aes(yintercept = mean(result) + 2 * sd(result)), colour = "red", linetype = "dashed") +
geom_hline(aes(yintercept = mean(result) - 2 * sd(result)), colour = "red", linetype = "dashed") +
theme_classic() +
labs(
# the title above the plot, based on information in the filtered df
title = paste0("some title for identifier: ", unique(df$identifier)),
x = "Sample number",
y = "Result",
# the text below, based on data in the filtered data frame
caption = paste0("A short sentence about the mean result (", round(mean(df$result), 2), ") below the plot.")
) +
coord_cartesian(xlim = c(0, max(df$sample.no) + 2)) +
theme(
# configure the caption / sentence below
plot.caption=element_text(size=12, hjust = 0, margin = margin(t=20)),
# add some buffer at bottom as spacing between plots
plot.margin = margin(b=50)
)
}
plot_list <- purrr::map(unique(input.data$identifier),
function(x) {
# filter data before passing it to the plot function
input.data %>%
dplyr::filter(identifier == x) %>%
my_plot()
}
)
which produces a list of plots, which can be then be printed in a Rmd chunk like this.
```{r}
purrr::map(plot_list, ~plot(.x))
Let's consider my ggplot function for histogram:
library(ggplot2)
get_histogram <- function(vec, width) {
df <- data.frame(vec)
temp <- ggplot2::ggplot(df, aes(x = vec)) +
# Delete x axis name and add plot title
labs(
x = NULL,
title = "Empirical histogram vs standard normal density"
) +
# Center plot title
theme(plot.title = element_text(hjust = 0.5)) +
# Add histogram with respect to given bin width
geom_histogram(
binwidth = width,
aes(y = stat(density)),
fill = I("blue"),
col = I("red"),
alpha = I(.2)
) +
# Adding probability density function of standard normal distribution.
stat_function(fun = function(x) {
stats::dnorm(x, mean = 0, sd = 1)
})
temp
}
Let's see how it works:
get_histogram(rnorm(100), width = 0.4)
However I will see error:
no visible binding for global variable 'density'
when running pacakge checks. Do you know where is the problem? I tried to find it, but it seems that most of those errors is connected with dplyr package rather than ggplot
I'm trying to graph multiple nonlinear least squares regression in r in different colors based on the value of a variable.
However, I also display the equation of the last one, and I would like the color in the nonlinear regression corresponding to the equation to be black as well.
What I've tried is shown in the geom_smooth() layer - I tried to include an ifelse() statement, but this doesn't work because of reasons described here: Different between colour argument and aes colour in ggplot2?
test <- function() {
require(ggplot2)
set.seed(1);
master <- data.frame(matrix(NA_real_, nrow = 0, ncol = 3))
for( i in 1:5 ) {
df <- data.frame(matrix(NA_real_, nrow = 50, ncol = 3))
colnames(df) <- c("xdata", "ydata", "test")
df$xdata = as.numeric(sample(1:100, size = nrow(df), replace = FALSE))
df$ydata = as.numeric(sample(1:3, size = nrow(df), prob=c(.60, .25, .15), replace = TRUE))
# browser()
df$test = i
master <- rbind(master, df)
}
df <- master
last <- 5
# based on https://stackoverflow.com/questions/18305852/power-regression-in-r-similar-to-excel
power_eqn = function(df, start = list(a=300,b=1)) {
m = nls(as.numeric(reorder(xdata,-ydata)) ~ a*ydata^b, start = start, data = df)
# View(summary(m))
# browser()
# eq <- substitute(italic(hat(y)) == a ~italic(x)^b*","~~italic(r)^2~"="~r2*","~~p~"="~italic(pvalue),
eq <- substitute(italic(y) == a ~italic(x)^b*","~~italic('se')~"="~se*","~~italic(p)~"="~pvalue,
list(a = format(coef(m)[1], digits = 6), # a
b = format(coef(m)[2], digits = 6), # b
# r2 = format(summary(m)$r.squared, digits = 3),
se = format(summary(m)$parameters[2,'Std. Error'], digits = 6), # standard error
pvalue = format(summary(m)$coefficients[2,'Pr(>|t|)'], digits=6) )) # p value (based on t statistic)
as.character(as.expression(eq))
}
plot1 <- ggplot(df, aes(x = as.numeric(reorder(xdata,-ydata)), y = ydata ) ) +
geom_point(color="black", shape=1 ) +
# PROBLEM LINE
stat_smooth(aes(color=ifelse(test==5, "black", test)), method = 'nls', formula = 'y~a*x^b', method.args = list(start= c(a =1,b=1)),se=FALSE, fullrange=TRUE) +
geom_text(x = quantile(df$xdata)[4], y = max(df$ydata), label = power_eqn(df), parse = TRUE, size=4, color="black") + # make bigger? add border around?
theme(legend.position = "none", axis.ticks.x = element_blank() ) + #, axis.title.x = "family number", axis.title.y = "number of languages" ) # axis.text.x = element_blank(),
labs( x = "xdata", y = "ydata", title="test" )
plot1
}
test()
This is the graph I got.
I would like the line corresponding to the points and equation to be black as well. Does anyone know how to do this?
I do not want to use a scale_fill_manual, etc., because my real data would have many, many more lines - unless the scale_fill_manual/etc. can be randomly generated.
You could use scale_color_manual using a custom created palette where your level of interest (in your example where test equals 5) is set to black. Below I use palettes from RColorBrewer, extend them if necessary to the number of levels needed and sets the last color to black.
library(RColorBrewer) # provides several great palettes
createPalette <- function(n, colors = 'Greens') {
max_colors <- brewer.pal.info[colors, ]$maxcolors # Get maximum colors in palette
palette <- brewer.pal(min(max_colors, n), colors) # Get RColorBrewer palette
if (n > max_colors) {
palette <- colorRampPalette(palette)(n) # make it longer i n > max_colros
}
# assume that n-th color should be black
palette[n] <- "#000000"
# return palette
palette[1:n]
}
# create a palette with 5 levels using the Spectral palette
# change from 5 to the needed number of levels in your real data.
mypalette <- createPalette(5, 'Spectral') # palettes from RColorBrewer
We can then use mypalette with scale_color_manual(values=mypalette) to color points and lines according to the test variable.
Please note that I have updated geom_point and stat_smooth to so that they use aes(color=as.factor(test)). I have also changed the call to power_eqn to only use data points where df$test==5. The black points, lines and equation should now be based on the same data.
plot1 <- ggplot(df, aes(x = as.numeric(reorder(xdata,-ydata)), y = ydata )) +
geom_point(aes(color=as.factor(test)), shape=1) +
stat_smooth(aes(color=as.factor(test)), method = 'nls', formula = 'y~a*x^b', method.args = list(start= c(a =1,b=1)),se=FALSE, fullrange=TRUE) +
geom_text(x = quantile(df$xdata)[4], y = max(df$ydata), label = power_eqn(df[df$test == 5,]), parse = TRUE, size=4, color="black") +
theme(legend.position = "none", axis.ticks.x = element_blank() ) +
labs( x = "xdata", y = "ydata", title="test" ) +
scale_color_manual(values = mypalette)
plot1
See resulting figure here (not reputation enough to include them)
I hope you find my answer useful.
[enter image description here][1]I am trying to create a lowry plot in R but am having difficulty debugging the errors returned. I am using the following code to create the plot:
library(ggplot2)
library(reshape)
m_xylene_data <- data.frame(
Parameter = c(
"BW", "CRE", "DS", "KM", "MPY", "Pba", "Pfaa",
"Plia", "Prpda", "Pspda", "QCC", "QfaC", "QliC",
"QPC", "QspdC", "Rurine", "Vfac", "VliC", "Vmax"),
"Main Effect" = c(
1.03E-01, 9.91E-02, 9.18E-07, 3.42E-02, 9.27E-3, 2.82E-2, 2.58E-05,
1.37E-05, 5.73E-4, 2.76E-3, 6.77E-3, 8.67E-05, 1.30E-02,
1.19E-01, 4.75E-04, 5.25E-01, 2.07E-04, 1.73E-03, 1.08E-03),
Interaction = c(
1.49E-02, 1.43E-02, 1.25E-04, 6.84E-03, 3.25E-03, 7.67E-03, 8.34E-05,
1.17E-04, 2.04E-04, 7.64E-04, 2.84E-03, 8.72E-05, 2.37E-03,
2.61E-02, 6.68E-04, 4.57E-02, 1.32E-04, 6.96E-04, 6.55E-04
)
)
fortify_lowry_data <- function(data,
param_var = "Parameter",
main_var = "Main.Effect",
inter_var = "Interaction")
{
#Convert wide to long format
mdata <- melt(data, id.vars = param_var)
#Order columns by main effect and reorder parameter levels
o <- order(data[, main_var], decreasing = TRUE)
data <- data[o, ]
data[, param_var] <- factor(
data[, param_var], levels = data[, param_var]
)
#Force main effect, interaction to be numeric
data[, main_var] <- as.numeric(data[, main_var])
data[, inter_var] <- as.numeric(data[, inter_var])
#total effect is main effect + interaction
data$.total.effect <- rowSums(data[, c(main_var, inter_var)])
#Get cumulative totals for the ribbon
data$.cumulative.main.effect <- cumsum(data[, main_var])
data$.cumulative.total.effect <- cumsum(data$.total.effect)
#A quirk of ggplot2 means we need x coords of bars
data$.numeric.param <- as.numeric(data[, param_var])
#The other upper bound
#.maximum = 1 - main effects not included
data$.maximum <- c(1 - rev(cumsum(rev(data[, main_var])))[-1], 1)
data$.valid.ymax <- with(data,
pmin(.maximum, .cumulative.total.effect)
)
mdata[, param_var] <- factor(
mdata[, param_var], levels = data[, param_var]
)
list(data = data, mdata = mdata)
}
lowry_plot <- function(data,
param_var = "Parameter",
main_var = "Main.Effect",
inter_var = "Interaction",
x_lab = "Parameters",
y_lab = "Total Effects (= Main Effects + Interactions)",
ribbon_alpha = 0.5,
x_text_angle = 25)
{
#Fortify data and dump contents into plot function environment
data_list <- fortify_lowry_data(data, param_var, main_var, inter_var)
list2env(data_list, envir = sys.frame(sys.nframe()))
p <- ggplot(data) +
geom_bar(aes_string(x = param_var, y = "value", fill = "variable"),
data = mdata) +
geom_ribbon(
aes(x = .numeric.param, ymin = .cumulative.main.effect, ymax =
.valid.ymax),
data = data,
alpha = ribbon_alpha) +
xlab(x_lab) +
ylab(y_lab) +
scale_y_continuous(labels = "percent") +
theme(axis.text.x = text(angle = x_text_angle, hjust = 1)) +
scale_fill_grey(end = 0.5) +
theme(legend.position = "top",
legend.title =blank(),
legend.direction = "horizontal"
)
p
}
m_xylene_lowry <- lowry_plot(m_xylene_data)
When I run the code, it is giving me the following error:
Error: argument "x" is missing, with no default
It is not specific enough for me to know what the issue is. What is causing the error to be displayed and how can I make error statements more verbose?
Lowry PLOT
It seems that you have more than one faulty element in your code than just the error it throws. In my experience it always helps to first check whether the code works as expected before putting it into a function. The plotting-part below should work:
p <- ggplot(data) + # no need to give data here, if you overwrite it anyway blow, but does not affect outcome...
# geom_bar does the counting but does not take y-value. Use geom_col:
geom_col(aes_string(x = param_var, y = "value", fill = "variable"),
data = mdata,
position = position_stack(reverse = TRUE)) +
geom_ribbon(
aes(x = .numeric.param, ymin = .cumulative.main.effect, ymax =
.valid.ymax),
data = data,
alpha = ribbon_alpha) +
xlab(x_lab) +
ylab(y_lab) +
# use scales::percent_format():
scale_y_continuous(labels = scales::percent_format()) +
# text is not an element you can use here, use element_text():
theme(axis.text.x = element_text(angle = x_text_angle, hjust = 1)) +
scale_fill_grey(end = 0.5) +
# use element_blank(), not just blank()
theme(legend.position = "top",
legend.title = element_blank(),
legend.direction = "horizontal"
)
This at least plots something, but I'm not sure whether it is what you expect it to do. It would help if you could show the desired output.
Edit:
Added position = position_stack(reverse = TRUE) to order according to sample plot.
I have some charts created with ggplot2 which I would like to embed in a web application: I'd like to enhance the plots with tooltips. I've looked into several options. I'm currently experimenting with the rCharts library and, among others, dimple plots.
Here is the original ggplot:
Here is a first attempt to transpose this to a dimple plot:
I have several issues:
after formatting the y-axis with percentages, the data is altered.
after formatting the x-axis to correctly render dates, too many labels are printed.
I am not tied to dimple charts, so if there are other options that allow for an easier way to tweak axis formats I'd be happy to know. (the Morris charts look nice too, but tweaking them looks even harder, no?)
Objective: Fix the axes and add tooltips that give both the date (in the format 1984) and the value (in the format 40%).
If I can fix 1 and 2, I'd be very happy. But here is another, less important question, in case someone has suggestions:
Could I add the line labels ("Top 10%") to the tooltips when hovering over the lines?
After downloading the data from: https://gist.github.com/ptoche/872a77b5363356ff5399,
a data frame is created:
df <- read.csv("ps-income-shares.csv")
The basic dimple plot is created with:
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)
)
While basic, so far so good. However, the following command, intended to convert the y-data to percentages, alters the data:
p$yAxis(type = "addMeasureAxis", showPercent = TRUE)
What am I doing wrong with showPercent?
For reference, here is the ggplot code:
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
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/
EDIT:
Here is a screenshot of Ramnath's solution, with a title added and axis labels tweaked. Thanks 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
To change (rather than remove) axis labels, for instance:
myChart.axes[1].titleShape.text('Year')
To add a legend to the plot:
p$set(width = 1000, height = 600)
p$legend(
x = 580,
y = 0,
width = 50,
height = 200,
horizontalAlign = "left"
)
To save the rchart:
p$save("ps-us-top-income-shares.html", cdn = TRUE)
An alternative based on the nvd3 library can be obtained (without any of the fancy stuff) with:
df$Year <- strftime(df$Year, format = "%Y")
n <- nPlot(data = df, value ~ Year, group = 'Fractile', type = 'lineChart')
Here is one way to solve (1) and (2). The argument showPercent is not to add % to the values, but to recompute the values so that they stack up to 100% which is why you are seeing the behavior you pointed out.
At this point, you will see that we are still having to write custom javascript to tweak the x-axis to get it to display the way we want it to. In future iterations, we will strive to allow the entire dimple API to be accessible within 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
rCharts is rapidly evolving. I know it is late, but in case someone else would like to see it, here is an almost complete replication of the ggplot sample shown.
#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