Coloring scatter plot points differently based on certain conditions - plotly-dash

I have a scatter plot made using plotly.py and I would like to color certain points in the scatter plot with a different color based on a certain condition. I have attached a sample code below :
import plotly.plotly as py
import plotly.graph_objs as go
from plotly.offline import plot
data = [4.1, 2.1, 3.1, 4.4, 3.2, 4.1, 2.2]
trace_1 = go.Scatter(
x = [1, 2, 3, 4, 5, 6, 7],
y = data
)
layout = go.Layout(
paper_bgcolor='rgb(255,255,255)',
plot_bgcolor='rgb(229,229,229)',
title = "Sample Plot",
showlegend = False,
xaxis = dict(
mirror = True,
showline = True,
showticklabels = True,
ticks = 'outside',
gridcolor = 'rgb(255,255,255)',
),
yaxis = dict(
mirror = True,
showline = True,
showticklabels = False,
gridcolor = 'rgb(255,255,255)',
),
shapes = [{
'type': 'line',
'x0': 1,
'y0': 4,
'x1': len(data),
'y1': 4,
'name': 'First',
'line': {
'color': 'rgb(147, 19, 19)',
'width': 1,
'dash': 'longdash'
}
},
{
'type': 'line',
'x0': 1,
'y0': 3,
'x1': len(data),
'y1': 3,
'line': {
'color': 'rgb(147, 19, 19)',
'width': 1,
'dash': 'longdash'
}
}
]
)
fig = dict(data = [trace_1], layout = layout)
plot(fig, filename = "test_plot.html")
Here's the output Output Scatter plot
Here the long dashed horizontal lines have corresponding x values 4 & 3 respectively. As one can see, points 1, 2, 4, 6 and 7 lie outside the dashed lines. Is there a way to color them differently based on the condition (x > 3) and (x<4).
Here's a reference to something I found while searching for a solution :
Python Matplotlib scatter plot: Specify color points depending on conditions
How can I achieve this in plotly.py ?

You can accomplish this by using a numeric array to specify the marker color. See https://plot.ly/python/line-and-scatter/#scatter-with-a-color-dimension.
Adapting your particular example to display red markers below 3, green markers above 4, and gray markers between 3 and 4:
import plotly.graph_objs as go
from plotly.offline import init_notebook_mode, iplot
init_notebook_mode()
data = [4.1, 2.1, 3.1, 4.4, 3.2, 4.1, 2.2]
color = [
-1 if v < 3 else 1 if v > 4 else 0
for v in data
]
colorscale = [[0, 'red'], [0.5, 'gray'], [1.0, 'green']]
trace_1 = go.Scatter(
x = [1, 2, 3, 4, 5, 6, 7],
y = data,
marker = {'color': color,
'colorscale': colorscale,
'size': 10
}
)
layout = go.Layout(
paper_bgcolor='rgb(255,255,255)',
plot_bgcolor='rgb(229,229,229)',
title = "Sample Plot",
showlegend = False,
xaxis = dict(
mirror = True,
showline = True,
showticklabels = True,
ticks = 'outside',
gridcolor = 'rgb(255,255,255)',
),
yaxis = dict(
mirror = True,
showline = True,
showticklabels = False,
gridcolor = 'rgb(255,255,255)',
),
shapes = [{
'type': 'line',
'x0': 1,
'y0': 4,
'x1': len(data),
'y1': 4,
'name': 'First',
'line': {
'color': 'rgb(147, 19, 19)',
'width': 1,
'dash': 'longdash'
}
},
{
'type': 'line',
'x0': 1,
'y0': 3,
'x1': len(data),
'y1': 3,
'line': {
'color': 'rgb(147, 19, 19)',
'width': 1,
'dash': 'longdash'
}
}
]
)
fig = dict(data = [trace_1], layout = layout)
iplot(fig)
Hope that helps!

Related

Is there a way to plot Multiple Lines with Plotly.JS?

I am trying to use PLOTLY.JS to plot 2 line graphs. But nothing is showing up on the screen except an empty graph. Any help? It works fine with one lines, bar charts, etc.
var plot_data = {}
var trace1 = {
x: [4, 3, 1],
y: [1, 3, 6],mode: 'lines',
type: 'scatter'
};
var trace2 = {
x: [6, 8, 9],
y: [1, 2, 4],mode: 'lines',
type: 'scatter'
};
var data = [trace1, trace2];
plot_data.push(data);
var layout =
{
title: { text: 'Task Plot', font: { family: 'Courier New, monospace', size: 24 }, xref: 'paper', x: 0.05,}
};
//var config = {responsive : true};
Tester = document.getElementById('myDash');
Plotly.newPlot(Tester, plot_data, layout);
If you look at the documentation here, you'll want to pass an array of traces to Plotly.newPlot, so you can replace plot_data with data:
Plotly.newPlot(Tester, data, layout);

HTML horizontal bar chart with a goal line?

Is there a library that handles drawing an HTML horizontal bar chart, but with a goal line included, so the gap between the progress and the goal can be seen? I'd call this a 'horserace bar chart', but apparently no one else does.
Something like this:
you can use the library Chart.js
Example: Here is the jquery code to draw a horizontal line.
var data = {
labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"],
datasets: [{
data: [12, 3, 2, 1, 8, 8, 2, 2, 3, 5, 7, 1]
}]
};
var ctx = document.getElementById("LineWithLine").getContext("2d");
Chart.types.Line.extend({
name: "LineWithLine",
initialize: function () {
Chart.types.Line.prototype.initialize.apply(this, arguments);
},
draw: function () {
Chart.types.Line.prototype.draw.apply(this, arguments);
var point = this.datasets[0].points[this.options.lineAtIndex]
var scale = this.scale
console.log(this);
// draw line
this.chart.ctx.beginPath();
this.chart.ctx.moveTo(scale.startPoint+12, point.y);
this.chart.ctx.strokeStyle = '#ff0000';
this.chart.ctx.lineTo(this.chart.width, point.y);
this.chart.ctx.stroke();
// write TODAY
this.chart.ctx.textAlign = 'center';
this.chart.ctx.fillText("TODAY", scale.startPoint + 35, point.y+10);
}
});
new Chart(ctx).LineWithLine(data, {
datasetFill : false,
lineAtIndex: 2
});

Attempting to reverse tooltips on plotly.js bar chart

I am new to plotly.js. I reversed the bars in the bar chart, but the labels are currently staying in the same place. I want to replace the values that the
What I want is the labels in the jsfiddle. I want the y labels to display on the LEFT of the labels instead of the current spot at right labels and I would also like to display the x labels on the opposite side of the bar with the tooltip.
I hope this is clear. Thanks
Here is the jsfiddle.
https://jsfiddle.net/aj5qepv3/
var data = [{
type: 'bar',
x: [20, 14, 23],
y: ['giraffes', 'orangutans', 'monkeys'],
orientation: 'h'
}];
var layout = {
xaxis:{
autorange:'reversed'
},
yaxis:{
side:'right'
}
}
Plotly.newPlot('tester', data, layout);
Does this help you?
var data = [{
type: 'bar',
x: [20, 14, 23],
y: ['giraffes', 'orangutans', 'monkeys'],
orientation: 'h'
}];
var layout = {
xaxis:{
autorange:'reversed'
},
yaxis:{
side:'left'
},
xaxis:{
side:'top'
}
}
Plotly.newPlot('tester', data, layout);
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
<script src="https://d14fo0winaifog.cloudfront.net/plotly-basic.js"></script>
<div id="tester" style="width:600px;height:250px;"></div>

Google Visualization Column Chart specify Target line as Certainty role

When i put this below code i came with on visualization playground i get the Goal/Target line, but i want it to be dashed/dotted which requires certainty role as specified in the docs. Can anyone enlighten me how to do it with a array input to Google Datatable, or Datatable json string format
Code
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Year', 'Red', 'Yellow', 'Green','Target'],
['2003', 20, 0, 0,80],
['2004', 0, 55, 0,80],
['2005', 0, 0, 80,80],
['2005', 0, 0, 85,80]
]);
// Create and draw the visualization.
new google.visualization.ColumnChart(document.getElementById('visualization')).
draw(data,
{title:"Yearly Coffee Consumption by Country",
width:600, height:400,
hAxis: {title: "Year"},
legend:'none',
colors:['red','yellow','green'],
//isStacked: true,
series:{
3:{type:'steppedArea',areaOpacity:0}
}
//interpolateNulls: true
}
);
}​
Update
I got it to this level below, with the code but how do i make the line stretch graph width
function drawVisualization() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Month'); // Implicit domain label col.
data.addColumn('number', 'Sales'); // Implicit series 1 data col.
data.addColumn({type:'number'}); // interval role col.
data.addColumn({type:'number'}); // interval role col.
data.addColumn({type:'number'}); // interval role col.
data.addColumn({type:'boolean',role:'certainty'}); // certainty col.
data.addRows([
['Red',20, 0,0, 80,true],
['Yellow', 0, 55, 0, 80,false],
['Green', 0, 0, 85, 80,false]
]);
// Create and draw the visualization.
new google.visualization.ColumnChart(document.getElementById('visualization')).
draw(data,
{title:"Yearly Coffee Consumption by Country",
width:600, height:400,
hAxis: {title: "Year"},
legend:'none',
colors:['red','yellow','green'],
//isStacked: true,
series:{
3:{type:'line',areaOpacity:0}
}
//interpolateNulls: true
}
);
}​
PlayGround:
https://code.google.com/apis/ajax/playground/?type=visualization#column_chart
Roles Docs:
https://developers.google.com/chart/interactive/docs/roles
So what is the right JSON format for dashed lines?
Is there any, i mean anyway i can display a arrow indicator at the right corner of the Target line to visually indicate the Goal?
You can achieve this by creating empty columns at the beginning and end of your chart, and then setting the view window to be within the range that you actually want. The code below achieves this:
function drawVisualization() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Month'); // Implicit domain label col.
data.addColumn('number', 'Sales'); // Implicit series 1 data col.
data.addColumn({type:'number'}); // interval role col.
data.addColumn({type:'number'}); // interval role col.
data.addColumn({type:'number'}); // interval role col.
data.addColumn({type:'boolean',role:'certainty'}); // certainty col.
data.addRows([
['', null, null, null, 80, false],
['Red',20, 0,0, 80,true],
['Yellow', 0, 55, 0, 80,false],
['Green', 0, 0, 85, 80,false],
['', null, null, null, 80, true]
]);
// Create and draw the visualization.
new google.visualization.ColumnChart(document.getElementById('visualization')).
draw(data,
{title:"Yearly Coffee Consumption by Country",
width:600, height:400,
hAxis: {title: "Year"},
legend:'none',
colors:['red','yellow','green'],
//isStacked: true,
series:{
3:{type:'line',areaOpacity:0}
},
hAxis: {
viewWindow: {
min: 1,
max: 4
}
}
//interpolateNulls: true
}
);
}
​

Kineticjs load json canvas

I always got the error:
"TypeError: Kinetic[type] is not a constructor"
"ReferenceError: reference to undefined property obj.nodeType"
when i try to load one json.
json = stage.toJSON();
stage = Kinetic.Node.create(json, 'myCanvas');
the method _createNode from Kineticjs 4.3.3
var no = new Kinetic[type](obj.attrs);
on my canvas I have a simple group
var circle1 = new Kinetic.Circle({
x: 40,
y: 50,
radius: 42,
fill: 'white',
stroke: 'black',
strokeWidth: 1,
draggable: false
});
var polygon1Tab1 = new Kinetic.RegularPolygon({
x: 40,
y: 50,
radius: 27,
sides: 4,
stroke: 'black',
strokeWidth: 4,
draggable: false
});
polygon1Tab1.rotateDeg(45);
var group1 = new Kinetic.Group({
draggable: true,
});
group1.add(circle1.clone());
group1.add(polygon1.clone());
What is "polygon1" here?
group1.add(polygon1.clone());
I created this example. Everything forks fine: http://jsfiddle.net/lavrton/N3UPX/
'polygon1' It's just one name ... a change!!!!
I take your code and place to run and continue with the same error!
when i print the json I noticed that it has an error!
he puts this "children": "[]" and should not have quotes in brackets
if I copy and put my string this fixed string corrected wheel normal!!
I made a method to remove the error .... Now I'm with an error
SyntaxError: JSON.parse: expected property name or '}'
var json = polygonLayer.toJSON();
json = json.replace('"children":"', '"children":');
json = json.substring(0, json.length-2) + json.substring(json.length-1, json.length);
whereas using the same fixed string works!
I'm using version 4.3.3
this work
var json = '{"attrs":{"clearBeforeDraw":true,"visible":true,"listening":true,"opacity":1,"x":0,"y":0,"scale":{"x":1,"y":1},"rotation":0,"offset":{"x":0,"y":0},"draggable":false,"dragOnTop":true},"nodeType":"Layer","children":[{\"attrs\": {\"width\": 600, \"height\": 400, \"cornerRadius\": 0, \"fillEnabled\": true, \"strokeEnabled\": true, \"shadowEnabled\": true, \"dashArrayEnabled\": true, \"fillPriority\": \"color\", \"visible\": true, \"listening\": true, \"opacity\": 1, \"x\": 0, \"y\": 0, \"scale\": {\"x\": 1, \"y\": 1}, \"rotation\": 0, \"offset\": {\"x\": 0, \"y\": 0}, \"draggable\": false, \"dragOnTop\": true, \"fill\": \"white\"}, \"nodeType\": \"Shape\", \"shapeType\": \"Rect\"}]}';
layer = Kinetic.Node.create(json, 'canvas');
but this dont work
var json = layer.toJSON();
layer = Kinetic.Node.create(json, 'canvas');