Error in FUN(X[[i]], ...) : object 'Year' not found when plotting ordination in ggplot - ggplot2

I am having an issue with the ggplot code line where R doesn't like the "group = Year".
Here is what my data looks like:
> head(data.scores.pa)
NMDS1 NMDS2 NMDS3 Site Year Elevation Fire history
1 -0.737547 0.73473457 0.7575643 BF 2004 1710 Burnt
......
> head(spp.scrs2)
species MDS1 MDS2 pval
1 Acrothamnus.montanus 0.8383 -0.02382347 1e-04
........
> head(vec.sp.df.pa)
MDS1 MDS2 species pvals
Elevation 0.834847 0.747474 Elevation 0.005
Here is the code I am using:
>xy <- ggplot(data.scores.pa, aes(x = NMDS1, y = NMDS2, group = Year)) +
geom_point(size = 3, aes(shape = Fire history, colour = Year))+
stat_ellipse(mapping = NULL, data = NULL, geom = "path", position = "identity", type = "t", level = 0.95, segments = 51, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE) +
geom_segment(data=vec.sp.df.pa, aes(x=0,xend=MDS1,y=0,yend=MDS2),
arrow = arrow(length = unit(0.5,"cm")),colour="grey")+
geom_text_repel(data=vec.sp.df.pa,aes(x=MDS1,y=MDS2,label=species),size=2)+
geom_segment(data=spp.scrs2,aes(x=0,xend=MDS1,y=0,yend=MDS2),
arrow = arrow(length = unit(0.5, "cm")),colour="black")+
geom_text_repel(data=spp.scrs2, aes(x=MDS1,y=MDS2,label=species),size=2)+
annotate("text", x = -1.6, y = 1, label = paste0("3D stress: ", format(ord.pa$stress, digits = 4)), hjust = 0) +
theme_cowplot() + scale_color_brewer(palette = "BrBG", direction = 1) +
theme(panel.border = element_rect(colour = "black"))+
ggtitle("All Sites - distance data using Bray-Curtis")+
labs(x = "NMDS1", y = "NMDS2")
> Error in FUN(X[[i]], ...) : object 'Year' not found
However, when I remove the geom_segment and geom_text_repel code lines it fixes the problem and I am able to plot the graph...
Is anyone able to provide some insight into this issue?
Thank you!

Related

Expand margins of ggplot

Apologies for the simplistic question, but I'm having trouble adjusting the size (width) of this plot to include all the data so that it doesn't look so squished. I've tried adjusting the margins and the width in png(), but nothing seems to work.
png("file_name.png", units = "in", width = 10, height = 5, res = 300)
ggplot(pred, aes(x = Longitude, y = Latitude)) +
geom_raster(aes(fill = Fitted)) +
facet_wrap(~ CYR) +
scale_fill_viridis(option = 'plasma',
na.value = 'transparent') +
coord_quickmap() +
theme(legend.position = 'top')
# theme(plot.margin=grid::unit(c(0,20,0,20), "mm"))
dev.off()
Do you need to use coord_quickmap() for some reason? Removing it 'fixes' the plot dimensions, e.g. using the palmerpenguins dataset:
library(ggplot2)
library(palmerpenguins)
p1 <- ggplot(penguins, aes(x = sex,
y = bill_length_mm,
fill = bill_depth_mm)) +
geom_raster() +
scale_fill_viridis_c(option = 'plasma',
na.value = 'transparent') +
facet_wrap(~interaction(island, species, year)) +
theme(legend.position = 'top') +
coord_quickmap()
p1
#> Warning: Raster pixels are placed at uneven horizontal intervals and will be shifted
#> ℹ Consider using `geom_tile()` instead.
#> Warning: Removed 2 rows containing missing values (`geom_raster()`).
p2 <- ggplot(penguins, aes(x = sex,
y = bill_length_mm,
fill = bill_depth_mm)) +
geom_raster() +
scale_fill_viridis_c(option = 'plasma',
na.value = 'transparent') +
facet_wrap(~interaction(island, species, year)) +
theme(legend.position = 'top') #+
# coord_quickmap()
p2
#> Warning: Raster pixels are placed at uneven horizontal intervals and will be shifted
#> ℹ Consider using `geom_tile()` instead.
#> Removed 2 rows containing missing values (`geom_raster()`).
Created on 2023-02-13 with reprex v2.0.2

ggplot show the value rounded to one decimal place above the bar chart

I want to round the values above the bar chart to one decimal place. For example 14 should be 1.5 and not 1.52977.
This is how the bar chart looks right now
This is my code:
CPUE1 <- CPUE
CPUE1$Strecke <- factor (CPUE1$Strecke, levels = c('30/31', '14', '12', '10','1c','1bc', '1b'))
ggplot(CPUE1, aes(x= Strecke, y= CPUE, fill = Strecke ))+
geom_bar(stat='identity', position = 'dodge')+
theme_minimal()+
geom_text (aes (label = CPUE), position=position_dodge(width=0.9), vjust=-0.25)+
scale_fill_manual (values =
c("12" = "green", "10"= "green",
"1c" = "green", "14"= "red",
"1b"= "red","1bc"= "red","30/31" = "red"))
Add round to your geom_text:
library(tidyverse)
tribble(
~Strecke, ~CPUE,
"1b", 1.333,
"1c", 1.222,
"1b", 2.666,
"1c", 2.777
) |>
mutate(Strecke = factor(Strecke)) |>
ggplot(aes(Strecke, CPUE, fill = Strecke)) +
geom_bar(stat = "identity", position = "dodge") +
theme_minimal() +
geom_text(aes(label = round(CPUE, 1)), position = position_dodge(width = 0.9), vjust = -0.25) +
scale_fill_manual(values = c("1b" = "red", "1c" = "blue"))
Created on 2022-07-07 by the reprex package (v2.0.1)

Changing x-axis tick labels in reverse plot

I try to have an axis going from 0 to 24 (that represent hours in a day). With tick labels at 6, 12 and 18 too.
I am struggling, I tried already scale_x_discrete and scale_x_continuous and ylim, but the axis always goes from 0 to 25... :(
Thanks in avance for your help
Categ <- c("Employment","Voluntary work","Householdchores","Household member care","Personal care","Study","Sports and outdoor",
"Leisure","Travel or unspecified","Sleep")
Regime <- c("Unemp.", "Part-time 1" ,"Part-time 2" ,"Full time" , "Overtime")
Share <- c(0.00,0.10,3.71,1.14,2.70,0.18,0.37,5.55,1.28,8.96,1.29,0.10,4.13,1.13,3.10,0.11,0.18,3.73,1.72,8.50,3.79,0.13,2.89,0.78,2.43,0.04,0.22,3.94,1.69,8.09,5.78,0.08,1.96,
0.76,2.17,0.03,0.24,3.44,1.48,8.05,7.88,0.10,1.46,0.57,1.91,0.02,0.20,2.73,1.33,7.80)
data <- data.frame(Regime = rep(rev(Regime), each=10),
Category = rep(Categ,times=5),
Share = Share)
pct2 <- ggplot(data,
aes(x = Regime, y = Share)) +
geom_bar(aes(fill = Category),
stat = "identity", colour="black")+
coord_flip() +
theme(panel.background = element_blank()) +
scale_fill_manual("Legend", values = c("Employment" = "#F4A582", "Voluntary work" = "#FDDBC7", "Household chores" = "#92C5DE", "Household member care" = "#4393C3", "Personal care" = "#737373", "Study" = "#969696", "Sports and outdoor" = "#BDBDBD", "Leisure" = "#D9D9D9", "Travel or unspecified"= "#F0F0F0", "Sleep" = "#F6E8C3")) +
ylim(0,24)
print(pct2)
This should do (I'm adding scale_y_continuous(...) and I'm omitting ylim(0,24):
ggplot(data, aes(x = Regime, y = Share)) +
geom_bar(aes(fill = Category), stat = "identity", colour="black") +
coord_flip() +
scale_y_continuous(breaks = as.numeric(seq(1:24))) +
theme(panel.background = element_blank()) +
scale_fill_manual("Legend", values = c("Employment" = "#F4A582", "Voluntary work" = "#FDDBC7", "Household chores" = "#92C5DE", "Household member care" = "#4393C3", "Personal care" = "#737373", "Study" = "#969696", "Sports and outdoor" = "#BDBDBD", "Leisure" = "#D9D9D9", "Travel or unspecified"= "#F0F0F0", "Sleep" = "#F6E8C3"))

I want to find the highest price since entry in pine script?

I want to find the highest price and exit when current price is lower than highest price. The code to find the highest price is copied from here. how can I make a simpler code that finds highest price since entry? I also want to close the deal if current price is lower than a specific price. Please help me.
// SETTING //
length1=input(1)
length3=input(3)
length7=input(7)
length20=input(20)
length60=input(60)
length120=input(120)
ma1= sma(close,length1)
ma3= sma(close,length3)
ma7= sma(close,length7)
ma20=sma(close,length20)
ma60=sma(close,length60)
ma120=sma(close,length120)
rsi=rsi(close,14)
// BUYING VOLUME AND SELLING VOLUME //
BV = iff( (high==low), 0, volume*(close-low)/(high-low))
SV = iff( (high==low), 0, volume*(high-close)/(high-low))
vol = iff(volume > 0, volume, 1)
dailyLength = input(title = "Daily MA length", type = input.integer, defval = 50, minval = 1, maxval = 100)
weeklyLength = input(title = "Weekly MA length", type = input.integer, defval = 10, minval = 1, maxval = 100)
//-----------------------------------------------------------
Davgvol = sma(volume, dailyLength)
Wavgvol = sma(volume, weeklyLength)
//-----------------------------------------------------------
length = input(20, minval=1)
src = input(close, title="Source")
mult = input(2.0, minval=0.001, maxval=50, title="StdDev")
mult2= input(1.5, minval=0.001, maxval=50, title="exp")
mult3= input(1.0, minval=0.001, maxval=50, title="exp1")
basis = sma(src, length)
dev = mult * stdev(src, length)
upper = basis + dev
lower = basis - dev
dev2= mult2 * stdev(src, length)
Supper= basis + dev2
Slower= basis - dev2
dev3= mult3 * stdev(src, length)
upper1= basis + dev3
lower1= basis - dev3
offset = input(0, "Offset", type = input.integer, minval = -500, maxval = 500)
plot(basis, "Basis", color=#FF6D00, offset = offset)
p1 = plot(upper, "Upper", color=#2962FF, offset = offset)
p2 = plot(lower, "Lower", color=#2962FF, offset = offset)
fill(p1, p2, title = "Background", color=color.rgb(33, 150, 243, 95))
//----------------------------------------------------
exit=(close-strategy.position_avg_price / strategy.position_avg_price*100)
bull=(low>upper and BV>SV and BV>Davgvol)
bux =(close<Supper and close>Slower and volume<Wavgvol)
bear=(close<Slower and close<lower and SV>BV and SV>Wavgvol)
hi=highest(exit,10)
// - INPUTS
ShowPivots = input(true, title="Show Pivot Points")
ShowHHLL = input(true, title="Show HH,LL,LH,HL markers on Pivots Points")
left = input(5, minval=1, title="Pivot Length Left Hand Side")
right = input(5, minval=1, title="Pivot Length Right Hand Side")
ShowSRLevels = input(true, title="Show S/R Level Extensions")
maxLvlLen = input(0, minval=0, title="Maximum S/R Level Extension Length (0 = Max)")
ShowChannel = input(false, title="Show Levels as a Fractal Chaos Channel")
//
ShowFB = input(true, title="Show Fractal Break Alert Arrows")
// Determine pivots
pvtLenL = left
pvtLenR = right
// Get High and Low Pivot Points
pvthi_ = pivothigh(high, pvtLenL, pvtLenR)
pvtlo_ = pivotlow(low, pvtLenL, pvtLenR)
// Force Pivot completion before plotting.
pvthi = pvthi_
pvtlo = pvtlo_
// ||-----------------------------------------------------------------------------------------------------||
// ||--- Higher Highs, Lower Highs, Higher Lows, Lower Lows -------------------------------------------||
valuewhen_1 = valuewhen(pvthi, high[pvtLenR], 1)
valuewhen_2 = valuewhen(pvthi, high[pvtLenR], 0)
higherhigh = na(pvthi) ? na : valuewhen_1 < valuewhen_2 ? pvthi : na
valuewhen_3 = valuewhen(pvthi, high[pvtLenR], 1)
valuewhen_4 = valuewhen(pvthi, high[pvtLenR], 0)
lowerhigh = na(pvthi) ? na : valuewhen_3 > valuewhen_4 ? pvthi : na
valuewhen_5 = valuewhen(pvtlo, low[pvtLenR], 1)
valuewhen_6 = valuewhen(pvtlo, low[pvtLenR ], 0)
higherlow = na(pvtlo) ? na : valuewhen_5 < valuewhen_6 ? pvtlo : na
valuewhen_7 = valuewhen(pvtlo, low[pvtLenR], 1)
valuewhen_8 = valuewhen(pvtlo, low[pvtLenR ], 0)
lowerlow = na(pvtlo) ? na : valuewhen_7 > valuewhen_8 ? pvtlo : na
// If selected Display the HH/LL above/below candle.
plotshape(ShowHHLL ? higherhigh : na, title='HH', style=shape.triangledown, location=location.abovebar, color=color.new(color.green,50), text="HH", offset=-pvtLenR)
plotshape(ShowHHLL ? higherlow : na, title='HL', style=shape.triangleup, location=location.belowbar, color=color.new(color.green,50), text="HL", offset=-pvtLenR)
plotshape(ShowHHLL ? lowerhigh : na, title='LH', style=shape.triangledown, location=location.abovebar, color=color.new(color.red,50), text="LH", offset=-pvtLenR)
plotshape(ShowHHLL ? lowerlow : na, title='LL', style=shape.triangleup, location=location.belowbar, color=color.new(color.red,50), text="LL", offset=-pvtLenR)
plot(ShowPivots and not ShowHHLL ? pvthi : na, title='High Pivot', style=plot.style_circles, join=false, color=color.green, offset=-pvtLenR, linewidth=3)
plot(ShowPivots and not ShowHHLL ? pvtlo : na, title='Low Pivot', style=plot.style_circles, join=false, color=color.red, offset=-pvtLenR, linewidth=3)
//Count How many candles for current Pivot Level, If new reset.
counthi = 0
countlo = 0
counthi := na(pvthi) ? nz(counthi[1]) + 1 : 0
countlo := na(pvtlo) ? nz(countlo[1]) + 1 : 0
pvthis = 0.0
pvtlos = 0.0
pvthis := na(pvthi) ? pvthis[1] : high[pvtLenR]
pvtlos := na(pvtlo) ? pvtlos[1] : low[pvtLenR]
hipc = pvthis != pvthis[1] ? na : color.new(color.red,50)
lopc = pvtlos != pvtlos[1] ? na : color.new(color.green,50)
// Show Levels if Selected
plot(ShowSRLevels and not ShowChannel and (maxLvlLen == 0 or counthi < maxLvlLen) ? pvthis : na, color=hipc, linewidth=1, offset=-pvtLenR , title="Top Levels",style=plot.style_circles)
plot(ShowSRLevels and not ShowChannel and (maxLvlLen == 0 or countlo < maxLvlLen) ? pvtlos : na, color=lopc, linewidth=1, offset=-pvtLenR , title="Bottom Levels",style=plot.style_circles)
// Show Levels as a Fractal Chaos Channel
plot(ShowSRLevels and ShowChannel ? pvthis : na, color=color.green, linewidth=1, style=plot.style_stepline, offset=0, title="Top Chaos Channel", trackprice=false)
plot(ShowSRLevels and ShowChannel ? pvtlos : na, color=color.red, linewidth=1, style=plot.style_stepline, offset=0, title="Bottom Chaos Channel", trackprice=false)
// //
float fixedHH = fixnan(higherhigh)
// add offset = -pvtLenR to move the plot to the left and match the HH points.
plot(fixedHH)
bool lowerThanHH = close < fixedHH
float closeHHDiff = abs(fixedHH - close)
if barstate.islast
label.new(bar_index, high + 3*tr, tostring(closeHHDiff), xloc.bar_index, color = color.gray, style = label.style_label_down)
// STRATEGY LONG //
if (bull and close>ma3 and ma20>ma60)
strategy.entry("Long",strategy.long,1)
if (higherhigh*0.80==close)`enter code here`
strategy.close("Long",1)
imInATrade = strategy.position size != 0
highestPriceAfterEntry = valuewhen(imInATrade, high, 0)
The code above finds the highest price after entry or when you're in a trade.

Background Color of grid.arrange in gridExtra

So I am trying to draw a few ggplots and their legend using gridExtra. The legend appears in the last cell on a white background - I would like to change the background color there, so that white background disappears. How can I do that?
Here's my code:
library(reshape)
library(ggplot2)
library(plyr)
library(wq)
library(gridExtra)
library(lattice)
library(grid)
testVisualization <- function()
{
set.seed(123)
xx <- sample(seq(from = 20, to = 50, by = 5), size = 50, replace = TRUE)
yy <- sample(seq(from = 1, to = 50), size = 50, replace = TRUE)
zz <- sample(seq(from = 1, to = 10, by = 1), size = 50, replace = TRUE)
dd <- data.frame(xx,yy,zz)
colRainbow <- rainbow(n, s = 1, v = 1, start = 0, end = max(1, n - 1)/n, alpha = 1)
gg <- ggplot() + geom_point(data=dd, aes(x=xx, y=yy, colour=zz))+
theme_custom()
lay2 <- rbind(c(1,1,1,1,1),
c(2,2,3,3,4))
legg1 <- g_legend(gg)
grid.arrange(
gg+guides(fill=FALSE, colour=FALSE, size=FALSE),
gg+guides(fill=FALSE, colour=FALSE, size=FALSE),
gg+guides(fill=FALSE, colour=FALSE, size=FALSE),
legg1,
layout_matrix=lay2)
}
theme_custom <- function()
{
theme(
plot.background = element_rect(fill = "#002B36", colour = "#002B36"),
panel.background = element_rect(fill = "#002B36"),
panel.background = element_rect(fill = "#002B36"),
legend.background = element_rect(fill="#002B36", colour = "#002B36"),
legend.margin = unit(c(-4, -4), "cm"),
legend.key = element_rect(fill="#002B36", colour ="#002B36"),
legend.text =element_text(colour = "#DCD427"),
legend.title=element_text(colour = "#DCD427")
)
}
g_legend<-function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
#+ legend.margin = unit(-0.5, "cm")
legend
}
Try this,
g_legend<-function(gg){
tmp <- ggplot_gtable(ggplot_build(gg))
id <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
leg <- tmp$grobs[[id]]
bkg <- leg[["grobs"]][[1]][["grobs"]][leg[["grobs"]][[1]][["layout"]][,"name"]=="background"][[1]][["gp"]][["fill"]]
leg <- gtable_add_grob(leg, grobs = rectGrob(gp=gpar(fill=bkg, col="red", lty=2)),
t=1, l=1, b=nrow(leg), r=ncol(leg), z=-1)
# no idea why, but the legend seems to have weird negative sizes
# that make the background overlap with neighbouring elements
# workaround: set those unidentified sizes to 1null
leg$widths[c(1,2,4,5)] <- unit(rep(1,4),"null")
leg$heights[c(1,2,4,5)] <- unit(rep(1,4),"null")
leg
}