Extending lines on pine-script - pivot

I've got this code that as it is now, is connecting the pivots high and the low ones but I'd like the lines to extend to create trend lines and to extend horizontally to create Support/Resistance lines as well.
In the image below you can see the blue lines that the script is now creating and the red ones that i created manually to explain what I'd like it to do.
Continuos red lines for trends and dashed for S/R
I tried using line.set_extend but this code extends the lines forever creating a very confusing chart. I'd like to be able to set a maximum length the lines can extend or even better, a maximum of trend lines that can be displayed at a single time. Unluckily this goes beyond my coding capabilities.
Hopefully some of you has the skills to help me.
Thank you :)
//#version=4
study("PivotsExt", overlay=true)
Barsleft = input(10)
Barsright = input(10)
ph = pivothigh(Barsleft, Barsright)
pl = pivotlow( Barsleft, Barsright)
ph_ext = ph
pl_ext = pl
if (ph)
ph_ext := ph
if (pl)
pl_ext := pl
plot(ph_ext, color= color.blue, offset=-Barsright)
plot(pl_ext, color= color.red, offset=-Barsright)

Here we declare your 2 variables holding the pivot levels on the first bar only using var, which makes their value persistent across bars. We also adapt the plot() calls so they don't plot a diagonal line when levels change:
//#version=4
study("PivotsExt", overlay=true)
Barsleft = input(10)
Barsright = input(10)
ph = pivothigh(Barsleft, Barsright)
pl = pivotlow( Barsleft, Barsright)
var ph_ext = ph
var pl_ext = pl
if (ph)
ph_ext := ph
if (pl)
pl_ext := pl
// plot(ph_ext, color= color.blue, offset=-Barsright, style = plot.style_circles)
plot(ph_ext, color= change(ph_ext) ? na : color.blue, offset=-Barsright)
plot(pl_ext, color= change(pl_ext) ? na : color.red, offset=-Barsright)

Related

How to map discrete colours in a Plotly Sunburst chart in r

I am very new to using plotly in rstudio and have come up against a problem with mapping discrete colours (stored as hex codes in the field color) to each of the slices in my ids field.
I have included my code below:
df %>%
plot_ly(
color = I("black"),
marker = list(colors = ~color)) %>%
add_trace(ids = df$ids,
labels = df$labels,
parents = df$parents,
type = 'sunburst',
maxdepth = -1,
domain = list(column = 0)) %>%
layout(sunburstcolorway = df$color)
This is the resulting sunburst diagram I get using this code, which is obviously not ideal:
Ideally the first four levels would have the same colour, and then different hex colour codes are used for slices that are labelled "Poor","Moderate","GwC" or "Good".
A csv file of my data frame used above is available here.
I finally managed to nut out how to map my colour field to the background colours on the sunburst chart - have updated the code in original post. All that was required was to insert the following code segment:
plot_ly(
marker = list(colors = ~color))
Below is the output chart:

Take Pivot Low/High and draw trendline

I am trying to take the most recent last two Pivot High points (and Low) and draw a trendline from the last Pivot High to the current Pivot high. Since the pivothigh() function has the left and right bars both set to 5 I can always assume my currect Pivot point is bar_index[5]. The problem I am having is how do I keep up the with last pivot point that came before the current pivot? Not sure if there is some way when a pivot point is reached and labeled on the chart you can somehow save that candle time so you can reference it in the line.new() function. Here is my current code but the following code is what I manually did to figure out the last pivot point. Instead of typing in 13 or 18 it should be a variable that holds the previous candle that was a pivot point.
bar_index[13] - botc, low[18]
showpivot = input(true, title="Show Pivot Points")
lb = input(5, title="Left Bars", minval=1)
rb = input(5, title="Right Bars", minval=1)
float top = na
float bot = na
top := pivothigh(lb, rb)
bot := pivotlow(lb, rb)
plotshape(top and showpivot, text="[PH]", style=shape.labeldown, color=color.white, textcolor=color.black, location=location.abovebar, transp=0, offset = -rb)
plotshape(bot and showpivot, text="[PL]", style=shape.labeldown, color=color.white, textcolor=color.black, location=location.belowbar, transp=0, offset = -rb)
topc = 0, botc = 0
topc := top ? lb : nz(topc[1]) + 1
botc := bot ? lb : nz(botc[1]) + 1
var line divl = na
var label lab = na
if bot and showpivot
line.delete(divl)
divl := line.new(bar_index[13] - botc, low[18], bar_index[5], low[lb] , color = color.lime, extend=extend.right)```
I found some code that answered my question
https://www.tradingview.com/script/eXUYLaGv-Trend-Lines-v2/

Change color and legend of plotLearnerPrediction ggplot2 object

I've been producing a number of nice plots with the plotLearnerPrediction function in the mlr package for R. They look like this. From looking into the source code of the plotLearnerPrediction function it looks like the color surfaces are made with geom_tile.
A plot can for example be made by:
library(mlr)
data(iris)
#make a learner
lrn <- "classif.qda"
#make a task
my.task <- makeClassifTask(data = iris, target = "Species")
#make plot
plotLearnerPrediction(learner = lrn, task = my.task)
Now I wish to change the colors, using another red, blue and green tone to match those of some other plots that I've made for a project. for this I tried scale_fill_continuous and scale_fill_manual without any luck (Error: Discrete value supplied to continuous scale) I also wish to change the legend title and the labels for each legend entry (Which I tried giving appropriate parameters to the above scale_fill's). There's a lot of info out there on how to set the geom_tile colours when producing the plot, but I haven't found any info on how to do this post-production (i.e. in somebody else's plot object). Any help would be much appreciated.
When you look into the source code you see how the plot is generated and then you can see which scale has to be overwritten or set.
In this example it's fairly easy:
g = plotLearnerPrediction(learner = lrn, task = my.task)
library(ggplot2)
g + scale_fill_manual(values = c(setosa = "yellow", versicolor = "blue", virginica = "red"))

Bokeh: Control colors on Donut chart

I am using Bokeh to create a series of pie charts with bokeh.charts.Donut. The charts are based off of subsets of the same DataFrame, and all have the same category labels. I want to ensure that the same categories are displayed in the same colors across the various charts, but I haven't been able to figure out a consistent way of controlling the colors.
Currently I am sorting my input DataFrames by the label, and passing the same array of colors to the palette property of Donut. This still does not work as intended. Code is as follows:
main_colors = ['#10A400','#DB5E11','#C8C500','#CF102E','#00AFA8','#82BC00','#A40D7A','#FF7100','#1349BB']
#split out youth health problems
for_youth_health = detailed_assessment_safety.loc[detailed_assessment_safety.youth_health_prob.notnull()]
youth_health_issues = pd.DataFrame(for_youth_health.youth_health_prob.str.split(' ').tolist())
for col in youth_health_issues.columns:
newcol = 'youth_health_prob_' + str(col)
youth_health_issues = youth_health_issues.rename(columns={col:newcol})
youth_health_trans = pd.melt(youth_health_issues)
youth_health_trans = youth_health_trans.loc[youth_health_trans.value.notnull()]
youth_health_trans['issue_text'] = youth_health_trans.value.map(map_health_issues)
youth_health_trans.drop('value',axis=1,inplace=True)
youth_health_trans.sort_values(by='issue_text',ascending=True,inplace=True)
#pie of youth health issues
youth_health_issues = Donut(youth_health_trans,label='issue_text',
values='variable',agg='count',plot_width=plot_width,
plot_height=plot_height,title='Reported Youth Health Issues',
color=main_colors)
hover = HoverTool(point_policy='follow_mouse')
hover.tooltips = [('Number Reported','#values'),('Health Issue','#issue_text')]
youth_health_issues.add_tools(hover)
#split out adult health problems
for_adult_health = detailed_assessment_safety.loc[detailed_assessment_safety.adult_health_prob.notnull()]
adult_health_issues = pd.DataFrame(for_adult_health.adult_health_prob.str.split(' ').tolist())
for col in adult_health_issues.columns:
newcol = 'adult_health_prob_' + str(col)
adult_health_issues = adult_health_issues.rename(columns={col:newcol})
adult_health_trans = pd.melt(adult_health_issues)
adult_health_trans = adult_health_trans.loc[adult_health_trans.value.notnull()]
adult_health_trans['issue_text'] = adult_health_trans.value.map(map_health_issues)
adult_health_trans.drop('value',axis=1,inplace=True)
adult_health_trans.sort_values(by='issue_text',ascending=True,inplace=True)
#pie of adult health issues
adult_health_issues = Donut(adult_health_trans,label='issue_text',
values='variable',agg='count',plot_width=plot_width,
plot_height=plot_height,title='Reported Adult Health Issues',
palette=main_colors)
hover = HoverTool(point_policy='follow_mouse')
hover.tooltips = [('Number Reported','#values'),('Health Issue','#issue_text')]
adult_health_issues.add_tools(hover)
What's the proper way to map the same categories of Donut charts to colors across multiple charts? The other idea that I had was inserting a column into the DataFrame that mapped label values to colors, and then passing that column as an argument to Donut, but I couldn't make that work either. Any help is much appreciated.
After some experimentation, it turns out that when you pass an array of colors to the palette argument of Donut, the colors are associated with the donut slices based on an alphabetical sort of the slice name. So, the first color in your array of palette colors will be associated with the slice with the alphabetically first name, etc.

two textplots in one plot

I have been trying to work with textplot in R and am unsure if my question is possible or not, I know that par() can't be used to place two textplots in one plot. I have been using a page and this code to try and figure things out.
My question is: Is it possible to have two textplots within the same plot?
For example, in the par(mfrow=c(1,1)) scenario below, plot 1 is a texplot of species length. Say I wanted to replicate that textplot twice in that plot. Is that possible?
based on this site:
http://svitsrv25.epfl.ch/R-doc/library/gplots/html/textplot.html
textplot(version)
data(iris)
par(mfrow=c(1,1))
info <- sapply( split(iris$Sepal.Length, iris$Species),
function(x) round(c(Mean=mean(x), SD=sd(x), N=gdata::nobs(x)),2) )
textplot( info, valign="top" )
title("Sepal Length by Species")
What I want to do is put a second textplot within that plot, underneath the original. For arguments sake, replicating that textplot twice in the plot.
Is this possible?
Thanks!
Maybe you've figured it out in the last four months but I thought I'd chip in an answer anyway.
The code provided is most of the way towards doing what you require already, you just have to provide some additional inputs to title() and/or par(). Namely specify that the title is to be above both of the plots by using title("your title", outer = TRUE) and you can further adjust the position of the title with an option in par(), use par(mfrow = c(2,1), oma = c(0,0,"top",0)). Hopefully this answers your question.
require('gplots')
data(iris)
info <- sapply(split(iris$Sepal.Length, iris$Species),
function(x) round(c(Mean = mean(x), SD = sd(x), N = gdata::nobs(x)),2))
## Replace top with a numerical value to control the position of the title with respect to the
## top of the page.
par(mfrow = c(2,1), oma = c(0,0, top ,0))
textplot(info, valign = "top")
textplot(info, valign = "top")
title("Sepal Length by Species", outer = TRUE)

Resources