Here is a reproducible example
#load the packages
library(easypackages)
packages("tidyverse","readxl","sf","tmaptools","tmap","lubridate",
"lwgeom","Cairo","nngeo","purrr","scales", "ggthemes","janitor")
polls<-st_as_sf(read.csv(url("https://www.caerphilly.gov.uk/CaerphillyDocs/FOI/Datasets_polling_stations_csv.aspx")),
coords = c("Easting","Northing"),crs = 27700)%>%
mutate(date = sample(seq(as.Date('2020/01/01'), as.Date('2020/05/31'), by="day"), 147))
test_stack<-polls%>%st_join(polls%>%st_buffer(dist=1000),join=st_within)%>%
filter(Ballot.Box.Polling.Station.x!=Ballot.Box.Polling.Station.y)%>%
add_count(Ballot.Box.Polling.Station.x)%>%
rename(number_of_neighbours = n)%>%
mutate(interval_date = date.x-date.y)%>%
subset(select = -c(6:8,10,11,13:18))## removing this comment will summarise the data so that only number of neighbours is returned %>%
distinct(Ballot.Box.Polling.Station.x,number_of_neighbours,date.x)%>%
filter(number_of_neighbours >=2)
polls%>%mutate(id = as.numeric(row_number()))%>% mutate(thing = case_when(id %% 2 == 0 ~ "stuff",
id %% 2 !=0 ~ "type"))->polls
qtm(polls)
tmap_mode("view")
tm_shape(polls) + tm_markers(col = "thing")
tm_shape(polls) + tm_dots(col ="thing", size = 0.75)
what I'd like to do is change the colour and size of tm_markers, because in the thing I want to use it in it would be nice to make use of different colour markers easily.
Linked to this, is understanding how the clustering of markers works when the map mode is "view" and an html is generated.
Any help on tm_marker behaviour and tm_marker clustering would be brilliant.
thanks == "MANY!"
In the end it turns out to be much simpler than using markers. I don't like "markers", aesthetically, but I do like "dots" and tm_dots lets you sort out the colours more easily (or in my head it's easier..) . And the thing is. Well. Clustering can be applied to dots, bubbles, and tm_symbols.
It's all in here:
https://cran.r-project.org/web/packages/tmap/tmap.pdf
(p 89/90)
ANYWAY
tm_shape(polls) + tm_dots(col ="thing", size = 0.75,clustering = T)
that's the answer (for me). I can cluster and then colour by a field.
Related
I have 11 plots and used a looping function to plot them see my code below. However, I can't get them to fit in just 1 page or less. The plots are actually too big. I am using R software and writing my work in RMarkdown. I have spent almost an entire week trying to resolve this.
group_by(Firm_category) %>%
doo(
~ggboxplot(
data =., x = "Means.type", y = "means",
fill ="grey", palette = "npg", legend = "none",
ggtheme = theme_pubr()
),
result = "plots"
)
graph3
# Add statistical tests to each corresponding plot
Firm_category <- graph3$Firm_category
xx <- for(i in 1:length(Firm_category)){
graph3.i <- graph3$plots[[i]] +
labs(title = Firm_category[i]) +
stat_pvalue_manual(stat.test[i, ], label = "p.adj.signif")
print(graph3.i)
}
#output3.long data sample below as comments
#Firm_category billmonth Means.type means
#Agric 1 Before 38.4444
#Agric 1 After 51.9
Complete data is on my github: https://github.com/Fridahnyakundi/Descriptives-in-R/blob/master/Output3.csv
This code prints all the graphs but in like 4 pages. I want to group them into a grid. I have tried to add all these codes below just before my last curly bracket and none is working, please help me out.
library(cowplot)
print(plot_grid(plotlist = graph3.i[1:11], nrow = 4, ncol = 3))
library(ggpubr)
print(ggarrange(graph3.i[1:11], nrow = 4, ncol = 3))
I tried the gridExtra command as well (they all seem to do the same thing). I am the one with a mistake and I guess it has to do with my list. I read a lot of similar work here, some suggested
dev.new()
dev.off()
I still didn't get what they do. But adding either of them caused my code to stop.
I tried defining my 'for' loop function say call it 'XX', then later call it to make a list of graph but it returned NULL output.
I have tried defining an empty list (as I read in some answers here) then counting them to make a list that can be printed but I got so many errors.
I have done this for almost 3 days and will appreciate your help in resolving this.
Thanks!
I tried to complete your code ... and this works (but I don't have your 'stat.test' object). Basically, I added a graph3.i <- list() and replaced graph3.i in the loop ..
Is it what you wanted to do ?
library(magrittr)
library(dplyr)
library(rstatix)
library(ggplot2)
library(ggpubr)
data <- read.csv(url('http://raw.githubusercontent.com/Fridahnyakundi/Descriptives-in-R/master/Output3.csv'))
graph3 <- data %>% group_by(Firm_category) %>%
doo(
~ggboxplot(
data =., x = "Means.type", y = "means",
fill ="grey", palette = "npg", legend = "none",
ggtheme = theme_pubr()
),
result = "plots"
)
graph3
# Add statistical tests to each corresponding plot
graph3.i <- list()
Firm_category <- graph3$Firm_category
xx <- for(i in 1:length(Firm_category)){
graph3.i[[i]] <- graph3$plots[[i]] +
labs(title = Firm_category[i]) # +
# stat_pvalue_manual(stat.test[i, ], label = "p.adj.signif")
print(graph3.i)
}
library(cowplot)
print(plot_grid(plotlist = graph3.i[1:11], nrow = 4, ncol = 3))
I've asked a similar question late last year but couldn't find the time to work on that project until now.
So in the code below, I make a map of the bikes available in Paris using live data. The idea I have is to make a loop of this over time (I read that loops take a while to run so I might not have to add a time component to this) and save each map under a different name to see the "flow" of bike availability over a day for example.
Where I'm stuck is that I don't know how to run a loop over this. I've tried "for" I've tried "while" I've tried to put this as a function and then loop it and while I'm sure this is feasible I'm just out of options.
If someone has an idea of how to do this or direct me towards a tutorial I'd be forever grateful.
Thanks!
sta.Paris <- read.csv(url("https://opendata.paris.fr/explore/dataset/velib-disponibilite-en-temps-reel/download/?format=csv&timezone=Europe/Berlin&use_labels_for_header=true"),sep=";")
sta.Paris1 <- sta.Paris %>% separate(Coordonnées.géographiques,into=c("lat","lon"),sep=",") %>%
mutate(lat=as.numeric(lat),lon=as.numeric(lon))
sta.Paris1[15] <- NULL
sta.Paris2 <- na.omit(sta.Paris1)
sta.Paris2$velorange = cut(sta.Paris2$Nombre.total.vélos.disponibles,
breaks = c(0,5,10,15,20,25,100), right=F,
labels = c("Tres peu [0-5)", "Peu [5-10)","Moyen [10-15)","Assez [15-20)","Beaucoup [20-25)", "Enormement [25-100)")
)
colorFactor(palette = c("azure2","yellow","orange","red","red4","black"), domain = sta.Paris2$velorange)
map.velib1 <- leaflet(data = sta.Paris2) %>%
addTiles(urlTemplate = "http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png") %>%
addCircleMarkers(~ lon,~ lat,
color = ~ pal(velorange),
popupOptions(T),
radius=~ 3 ,stroke = FALSE, fillOpacity = 0.7,popup = ~ sprintf("<b> Vélos dispos: %s</b>",as.character(Nombre.total.vélos.disponibles)))
map.velib1
I am trying to generate bar plots / columns using rCharts(v 0.4.2). My problem is that I have an year's worth of data and I need to group on Months. So in Total I have 12 bars that I need to display. However, I have only 9 unique colors after which the colors start repeating. I read this documentation and tried inserting
colors <- c('#7cb5ec','#434348', '#90ed7d', '#f7a35c','#8085e9','#f15c80', '#e4d354','#2b908f','#f45b5b','#91e8e1')
into my code and then calling it as follows :
c <- hPlot(x = 'Confi', y = 'n', data = tablefinalC, type = 'bar', group = 'Month',title = "Inccode By confi",
subtitle = "Bar Graph")
c$plotOptions(series = list(stacking = "normal",colors=paste0('colors'))
c$chart(backgroundColor = NULL)
c$set(dom = 'chart5')
However, I still get the same repetitive colors. So can someone please confirm how I can increase the amount of colors? Thanks in advance
You can create empty chart and then add series
Example
library(rCharts)
df=data.frame(x=1:10,y=-10:-1,z=letters[1:10],stringsAsFactors = F)
colors1=c( '#7cb5ec','#434348', '#90ed7d')
df$col=rep(colors1,round(nrow(df)/length(colors1),0)+1)[1:nrow(df)]
# Create new chart
a <- rCharts:::Highcharts$new()
# Set options
a$chart(type = "bar")
for(i in unique(df$z)){
a$series(name=i,stacking = "normal" ,color=df$col[df$z==i], data= rCharts::toJSONArray2(df[df$z==i,], json=F, names=T))
}
a#plot
Result
Update( re-read question)
if you want to add more colors custominze colors1 and df$col
df=data.frame(x=1:20,y=-20:-1,z=letters[1:20],stringsAsFactors = F)
colors1=c( '#0048BA','#B0BF1A','#7CB9E8','#C9FFE5','#B284BE',
'#5D8AA8','#00308F','#72A0C1','#AF002A','#F0F8FF',
'#84DE02','#E32636','#C46210','#EFDECD','#E52B50',
'#AB274F','#F19CBB','#AB274F','#D3212D','#3B7A57',
'#FFBF00','#FF7E00','#FF033E','#9966CC','#A4C639',
'#F2F3F4','#CD9575','#665D1E','#915C83','#841B2D'
)
df$col=colors1[1:nrow(df)]
Give you
Does anyone with experience using the bioconductor package: Gviz know how to add an AnnotationTrack directly over a DataTrack?
For example, in ggplot2 I can add to a prexitsting plot using + geom_text, but I haven't been able to locate a similar feature for Gviz
Thanks!
Although it's not exactly what you want, one possible solution is to add a HighlightTrack that covers your region of interest. Although this won't specifically label / add the key elements on to your DataTrack, it will help highlight the alignment between differing DataTracks.
Example:
library(Gviz)
library(GenomicRanges)
data(geneModels)
data(cpgIslands)
gen <- genome(cpgIslands)
chr <- 1
start <- 120005434
end <- 129695434
itrack <- IdeogramTrack(genome = gen, chromosome = chr)
gtrack <- GenomeAxisTrack()
grtrack <- GeneRegionTrack(geneModels, genome = gen, chromosome = chr, name = "foo")
htrack <- HighlightTrack(trackList = list(gtrack, grtrack), start = 121535434, end = 124535434, chromosome = chr)
plotTracks(list(itrack, htrack), from = start, to = end)
Graphical output
Although the grtrack is empty, it demonstrates how the HighlightTrack will span the specified DataTracks (in this case, grtrack and gtrack).
See the GViz documentation for more on info.
require(quantmod)
require(PerformanceAnalytics)
getSymbols(c('SP500', 'WAAA', 'WBAA'), src = 'FRED', from = '1950-01-01')
X <- na.omit(merge(to.weekly(SP500), WAAA, WBAA))
dWAAA <- diff(WAAA / 100, 1)
dWBAA <- diff(WBAA / 100, 1)
D <- 20
dP.WAAA <- - D * dWAAA
dP.WBAA <- - D * dWBAA
charts.PerformanceSummary(p = .99, R = dP.WAAA['1990-01-01/2012-08-17'],
methods = 'ModifiedES', width = 48)
charts.PerformanceSummary(p = .99, R = dP.WBAA['1990-01-01/2012-08-17'],
methods = 'ModifiedES', width = 48)
May you tell me any way to set colors' smoothing-transitions-sequential palette in order to replace default black color with something which looks nicer?
I would like something which is blue-based and changes blue variety starting from the 1st plot ending to the 3rd one.
Thanks,
See ?chart.TimeSeries. I believe that the options you want are likely:
element.color # for the boxes, axes, etc
# and
colorset # for the actual chart lines
# try
colorset = 'darkblue'
# or
colorset = 'lightblue'
# as an extra argument to charts.PerformanceSummary
The colorsets provide different colors for the different chart elements, and work best when you plot more than one series on the same chart, to compare an asset to an index or a peer group, for example.
A vertical color ramp in R is not possible using base graphics, and conveys no information anyway.