how to grey out other lines using Mouse hover? - colors

I'm trying to grey out other lines when i hover over one of them so far i have this:
from sklearn import datasets
data_wine = datasets.load_wine (as_frame = True).frame
new_data = data_wine.drop (['proline', 'magnesium'], axis = 1)
new_data = new_data.reset_index().melt(id_vars = ['index', 'target'])
hover = alt.selection(
type="single", on="mouseover", fields=["variable"], nearest=True
)
lineplot = alt.Chart(new_data).mark_line().encode(
alt.X("variable:N"),
alt.Y("value:Q"),
alt.Color ('target:N'),
alt.Detail ('index:N'),
).properties(width = 1000)
# nearest point
point = lineplot.mark_circle().encode(
opacity=alt.value(0)
).add_selection(hover)
# highlight
singleline = lineplot.mark_line().encode(
size=alt.condition(~hover, alt.value(0.5), alt.value(3))
)
point+singleline
it looks like this and while hovering the mouse the size changes and i couldn't replace size with Color:
how can i achieve this?

new_data = data_wine.drop (['proline', 'magnesium'], axis = 1)
new_data = new_data.reset_index().melt(id_vars = ['index', 'target'])
highlight = alt.selection(type='single', on='mouseover', fields=['target'], nearest=False, bind='legend')
selection = alt.selection_multi(fields=['target'], bind='legend', on='mouseover')
lineplot=alt.Chart(new_data).mark_line().encode(
alt.X("variable:N"),
alt.Y("value:Q"),
alt.Color ('target:N'),
alt.Detail ('index:N'),
).properties(width = 1000)
# nearest point
point = lineplot.mark_circle().encode(
opacity=alt.value(0)
).add_selection(highlight)
#highlight
singleline = lineplot.mark_line().encode(
opacity=alt.condition(selection, alt.value(0.7), alt.value(0.03))
#size=alt.condition(~highlight, alt.value(1), alt.value(3))
).add_selection(selection)
point + singleline

Related

Plotly : How to enable text label in line graph for the last value?

I am trying to build a graph where the line graph should show the value of only the last element in some beautiful formating.
line graph with no text at end
Now the current method of the text shows for all elements and is a straight text that creates a lot of collisions with different lines in the same graph and looks clumsy.
Will be very nice to achieve something as mentioned in the below image.
desired line graph with text
This is now handled through:
legendgroup = d.name
Plot 1: All
Plot 2: Deselect GOOG in the legend and see that the marker disappears as well:
Complet code:
# imports
import pandas as pd
import plotly.express as px
# data
df = px.data.stocks()
df = df.drop('AMZN', axis = 1)
colors = px.colors.qualitative.T10
# plotly
fig = px.line(df,
x = 'date',
y = [c for c in df.columns if c != 'date'],
template = 'plotly_dark',
color_discrete_sequence = colors,
title = 'Stocks',
)
# move legend
fig.layout.legend.x = -0.3
# add traces for annotations and text for end of lines
for i, d in enumerate(fig.data):
fig.add_scatter(x=[d.x[-1]], y = [d.y[-1]],
mode = 'markers+text',
text = d.y[-1],
textfont = dict(color=d.line.color),
textposition='middle right',
marker = dict(color = d.line.color, size = 12),
legendgroup = d.name,
showlegend=False)
fig.show()

Bokeh: Is there a way to set the styling for all figures at once?

I am coding for 20+ tabs to plot similar parameters and have been writing the styling for each figure separately. Is there a way to set the styling all at once for all figures?
p = figure(tools=TOOLS, x_axis_type='datetime',plot_height=400, plot_width=700,
outline_line_color = 'gray',
y_axis_label = 'Volts',
y_range = DataRange1d()
)
# Setting the second y axis range name and range
#p.extra_y_ranges = {"foo": Range1d(start=0, end=0.000006)}
p.extra_y_ranges = {"foo": DataRange1d()}
# Adding the second axis to the plot.
p.add_layout(LinearAxis(y_range_name="foo"), 'right')
a1=p.line(x='Time', y='340', line_color="darkcyan", line_width=1, source=source)
a11 = p.line(x='Time',y='StdDev', line_color = 'red', line_width=1, y_range_name="foo", source=source)
p.y_range.renderers=[a1]
p.extra_y_ranges['foo'].renderers = [a11]
tooltips=[( "Time", "#Time{%H:%M:%S}"),
("Y-value", "$y")]
formatt ={'Time':'datetime'}
p.add_tools(HoverTool(tooltips=tooltips, formatters=formatt, mode = 'mouse'))
p.title.text = "Plot Title "
p.title.text_color = "gray"
p.title.text_font = "arial"
p.title.text_font_style = "bold"
p.xgrid[0].grid_line_color=None
p.ygrid[0].grid_line_alpha=0.5
p.xaxis.axis_label = 'TimeStamp'
Following my way, I would essentially need to repeat above code 20+ times for each tab.

how to adjust width of bokeh heatmap and remove white space around

I would like to change the width of the heatmap cell so that its dimensions are square (even). Ideally, the cells are small and square so that I can fit several heatmaps with just one column of data. I want to reproduce something like this:
My current code makes one heatmap that is too wide and there is lots of white space, as well as a strange y position that cuts off the bottom cell. Not sure what's going on. Thanks.
def genHeatMap():
colours = ['#67d33d',
'#76d74f',
'#84da5f',
'#91de6e',
'#9ce17b',
'#a6e488',
'#b1e795',
'#bbeaa1',
'#91de6e',
'#9ce17b']
values = [1.0,
0.17647058823529413,
0.08021390374331551,
0.04054054054054054,
0.06,
0.07894736842105263,
0.07317073170731707,
0.05813953488372093,
0.1320754716981132,
0.0]
y_labels=['103', '134', '140', '185', '235', '292', '299', '431', '566', '659']
y = list(range(10))
x = ['a'] * 10
df = {'xs':x,'ys':y,'value':values,'colour':colours,'labels':y_labels}
p = figure(x_range='a',y_range=y_labels,plot_width=300,plot_height=300,
tooltips = [('CSID', f'#labels-103'), ('Tanimoto', '#value')])
p.rect('xs', 'ys', width=1, height=1, source=df,color='colour', line_color="black")
p.toolbar.logo = None
p.min_border_bottom = 20
p.min_border_left = 0
p.min_border_right = 0
p.min_border_top = 0
p.xaxis.major_tick_line_color = None
p.xaxis.minor_tick_line_color = None
p.xaxis.major_label_text_font_size = '0pt'
return p
Set p.x_range.range_padding = 0
https://docs.bokeh.org/en/latest/docs/reference/models/ranges.html#bokeh.models.ranges.FactorRange.range_padding

Bokeh – ColumnDataSource not updating whiskered-plot

I’m having issues with the following code (I’ve cut out large pieces but I can add them back in – these seemed like the important parts). In my main code, I set up a plot (“sectionizePlot”) which is a simple variation on another whiskered-plot
I’m looking to update them on the fly. In the same script, I’m using a heatmap (“ModifiedGenericHeatMap”) which updates fine.
Any ideas how I might update my whiskered-plot? Updating the ColumnDataSource doesn’t seem to work (which makes sense). I’m guessing that I am running into issues with adding each circle/point individually onto the plot.
One idea would be to clear the plot each time and manually add the points onto the plot, but it would need to be cleared each time, which I’m unsure of how to do.
Any help would be appreciated. I’m just a lowly Scientist trying to utilize Bokeh in Pharma research.
def ModifiedgenericHeatMap(source, maxPct):
colors = ["#75968f", "#a5bab7", "#c9d9d3", "#e2e2e2", "#dfccce", "#ddb7b1", "#cc7878", "#933b41", "#550b1d"]
#mapper = LinearColorMapper(palette=colors, low=0, high=data['count'].max())
mapper = LinearColorMapper(palette=colors, low=0, high=maxPct)
TOOLS = "hover,save,pan,box_zoom,reset,wheel_zoom"
globalDist = figure(title="derp",
x_range=cols, y_range=list(reversed(rows)),
x_axis_location="above", plot_width=1000, plot_height=400,
tools=TOOLS, toolbar_location='below')
globalDist.grid.grid_line_color = None
globalDist.axis.axis_line_color = None
globalDist.axis.major_tick_line_color = None
globalDist.axis.major_label_text_font_size = "5pt"
globalDist.axis.major_label_standoff = 0
globalDist.xaxis.major_label_orientation = pi / 3
globalDist.rect(x="cols", y="rows", width=1, height=1,
source=source,
fill_color={'field': 'count', 'transform': mapper},
line_color=None)
color_bar = ColorBar(color_mapper=mapper, major_label_text_font_size="5pt",
ticker=BasicTicker(desired_num_ticks=len(colors)),
# fix this via using a formatter with accounts for
formatter=PrintfTickFormatter(format="%d%%"),
label_standoff=6, border_line_color=None, location=(0, 0))
text_props = {"source": source, "text_align": "left", "text_baseline": "middle"}
x = dodge("cols", -0.4, range=globalDist.x_range)
r = globalDist.text(x=x, y=dodge("rows", 0.3, range=globalDist.y_range), text="count", **text_props)
r.glyph.text_font_size = "8pt"
globalDist.add_layout(color_bar, 'right')
globalDist.select_one(HoverTool).tooltips = [
('Well:', '#rows #cols'),
('Count:', '#count'),
]
return globalDist
def sectionizePlot(source, source_error, type, base):
print("sectionize plot created with typ: " + type)
colors = []
for x in range(0, len(base)):
colors.append(getRandomColor())
title = type + "-wise Intensity Distribution"
p = figure(plot_width=600, plot_height=300, title=title)
p.add_layout(
Whisker(source=source_error, base="base", upper="upper", lower="lower"))
for i, sec in enumerate(source.data['base']):
p.circle(x=source_error.data["base"][i], y=sec, color=colors[i])
p.xaxis.axis_label = type
p.yaxis.axis_label = "Intensity"
if (type.split()[-1] == "Row"):
print("hit a row")
conv = dict(enumerate(list("nABCDEFGHIJKLMNOP")))
conv.pop(0)
p.xaxis.major_label_overrides = conv
p.xaxis.ticker = SingleIntervalTicker(interval=1)
return p
famData = dict()
e1FractSource = ColumnDataSource(dict(count=[], cols=[], rows=[], index=[]))
e1Fract = ModifiedgenericHeatMap(e1FractSource, 100)
rowSectTotSource = ColumnDataSource(data=dict(base=[]))
rowSectTotSource_error = ColumnDataSource(data=dict(base=[], lower=[], upper=[]))
rowSectPlot_tot = sectionizePlot(rowSectTotSource,rowSectTotSource_error, "eSum Row", rowBase)
def update(selected=None):
global famData
famData = getFAMData(file_source_dt1, True)
global e1Stack
e1Fract = (famData['e1Sub'] / famData['eSum']) * 100
e1Stack = e1Fract.stack(dropna=False).reset_index()
e1Stack.columns = ["rows", "cols", "count"]
e1Stack['count'] = e1Stack['count'].apply(lambda x: round(x, 1))
e1FractSource.data = dict(cols=e1Stack["cols"], count=(e1Stack["count"]),
rows=e1Stack["rows"], index=e1Stack.index.values, codon=wells, )
rowData, colData = sectionize(famData['eSum'], rows, cols)
rowData_lower, rowData_upper = getLowerUpper(rowData)
rowBase = list(range(1, 17))
rowSectTotSource_error.data = dict(base=rowBase, lower=rowData_lower, upper=rowData_upper, )
rowSectTotSource.data = dict(base=rowData)
rowSectPlot_tot.title.text = "plot changed in update"
layout = column(e1FractSource, rowSectPlot_tot)
update()
curdoc().add_root(layout)
curdoc().title = "Specs"
print("ok")

Changing the attributes of the what appears when hovering over a Choropleth Map in plotly

I am using plotly in Python 3.6.3 and am trying to do a Choropleth map as in here. I would like to change the attributes of what appears when hovering above the map. That is, for example, if we consider the first map and hover of California, it looks like:
I want to change both the font size of the content that appears and the size of the box. Is there a way to access those?
Here is the code that generates it:
import plotly.plotly as py
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv')
for col in df.columns:
df[col] = df[col].astype(str)
scl = [[0.0, 'rgb(242,240,247)'],[0.2, 'rgb(218,218,235)'],[0.4, 'rgb(188,189,220)'],\
[0.6, 'rgb(158,154,200)'],[0.8, 'rgb(117,107,177)'],[1.0, 'rgb(84,39,143)']]
df['text'] = df['state'] + '<br>' +\
'Beef '+df['beef']+' Dairy '+df['dairy']+'<br>'+\
'Fruits '+df['total fruits']+' Veggies ' + df['total veggies']+'<br>'+\
'Wheat '+df['wheat']+' Corn '+df['corn']
data = [ dict(
type='choropleth',
colorscale = scl,
autocolorscale = False,
locations = df['code'],
z = df['total exports'].astype(float),
locationmode = 'USA-states',
text = df['text'],
marker = dict(
line = dict (
color = 'rgb(255,255,255)',
width = 2
) ),
colorbar = dict(
title = "Millions USD")
) ]
layout = dict(
title = '2011 US Agriculture Exports by State<br>(Hover for breakdown)',
geo = dict(
scope='usa',
projection=dict( type='albers usa' ),
showlakes = True,
lakecolor = 'rgb(255, 255, 255)'),
)
fig = dict( data=data, layout=layout )
py.iplot( fig, filename='d3-cloropleth-map' )
The chloropleth>hoverlabel function lets you set the background color, border color, and font. The size of the border box is determined by the text within it, however. If the name shows up as truncated it can be expanded with the chloropleth>hoverlabel>namelength function.

Resources