Streamlit bar chart conditional and background color - streamlit

I have the following code that display streamlit bar chart for one of our job. How do I display RED for error and GREEN for success ?. Each run tell us how long it took in mins and whether it is successful or not. 'S' = Success, 'F' = Fail. As you can see, i only able to show all color green. How do i use alt.condition to switch between bar color.
Second question is to how do I set the graph background to WHITE color not following the body background color which is now in lightgray ?
df = pd.DataFrame({
'runid': ['983232','98324', '1032019', '1042019',
'1052019','1062019', '1072019', '1082019',
'1092019','10102019', '10112019', '10122019',
'10132019','10142019', '10152019', '10162019'],
'duration': [5, 30, 3, 10,3.4,6,12,6,3,6,3,1,5,4.3,4,3],
'results': ['S','S','S','S','S','S','S','S','S','F','S','S','F','S','S','S']
})
c = alt.Chart(df).mark_bar().encode(
x='runid', y='duration', tooltip=['runid', 'duration'],
color=alt.value('#32a852'))
st.altair_chart(c, use_container_width=True)

You can try this:
df = pd.DataFrame({
'runid': ['983232','98324', '1032019', '1042019',
'1052019','1062019', '1072019', '1082019',
'1092019','10102019', '10112019', '10122019',
'10132019','10142019', '10152019', '10162019'],
'duration': [5, 30, 3, 10,3.4,6,12,6,3,6,3,1,5,4.3,4,3],
'results': ['S','S','S','S','S','S','S','S','S','F','S','S','F','S','S','S']
})
c = alt.Chart(df).mark_bar().encode(x='runid', y='duration', tooltip=['runid', 'duration'],
color=alt.condition(
alt.datum.results == "S",
alt.value("#32a852"),
alt.value("red")
)).configure(background='#FFFFFF')
st.altair_chart(c, use_container_width=True)

Related

Kusto - Conditional formating in Kusto

I have a Kusto Query where the result is in the table format. But when I apply the conditional format it does not highlight the cell with the correct color as per the rule I created.
for example--I have a column with duraion and set the rule as below
Green if > 0
Blue if > 1
Yellow if > 5
Red if > 20
But I see some of the cell that has value 2.5 is highlighted in Red . where the color should be blue. When I delete the rule for Red, the cell changes to Yellow color. Is there a solution for this or right way to apply rule.Thanks. This is projecting a wrong alert. Thanks for any inputs.
Screenshot of column with formating
some of the values are in red which should be in blue as per the rules (refer screenshot below)
You can see the rules below
datatable (AvgDuration: string, AvgDurationWin: string, AvgDurationLinux: string, MinDuration: string, MaxDuration: string) [
"0.0666 s","0.0732 s","0.0525 s","0.015 s","0.684 s",
"0.0663 s","0.0712 s","0.0535 s","0.015 s","0.851 s",
"0.0649 s","0.0700 s","0.0521 s","0.014 s","0.674 s",
"25.050 s","17.614 s","18.428 s","13.133 s","56.284 s",
"0.0982 s","0.1074 s","0.0805 s","0.021 s","1.078 s",
"0.0982 s","0.1046 s","0.0814 s","0.021 s","1.041 s",
"0.0982 s","0.1058 s","0.0813 s","0.021 s","1.106 s",
"0.0987 s","0.1089 s","0.0814 s","0.022 s","1.039 s",
"0.0992 s","0.1074 s","0.0817 s","0.022 s","1.032 s"
]
This is because your values are string. If you want to calculate it by seconds and have conditional formatting you can do the following:
Use the round() function to limit the number of digits after the dot
Indicate the unit in the column name
For example:
| summarize AvgDurationInSeconds = avgif round((Duration, Tests == "Success"), 2)

Python ArcPy - Print Layer with highest field value

I have some python code that goes through layers in my ArcGIS project and prints out the layer names and their corresponding highest value within the field "SUM_USER_VisitCount".
Output Picture
What I want the code to do is only print out the layer name and SUM_USER_VisitCount field value for the one layer with the absolute highest value.
Desired Output
I have been unable to figure out how to achieve this and can't find anything online either. Can someone help me achieve my desired output?
Sorry if the code layout is a little weird. It got messed up when I pasted it into the "code sample"
Here is my code:
import arcpy
import datetime
from datetime import timedelta
import time
#Document Start Time in-order to calculate Run Time
time1 = time.clock()
#assign project and map frame
p =
arcpy.mp.ArcGISProject(r'E:\arcGIS_Shared\Python\CumulativeHeatMaps.aprx')
m = p.listMaps('Map')[0]
Markets = [3000]
### Centers to loop through
CA_Centers = ['Castro', 'ColeValley', 'Excelsior', 'GlenPark',
'LowerPacificHeights', 'Marina', 'NorthBeach', 'RedwoodCity', 'SanBruno',
'DalyCity']
for Market in Markets:
print(Market)
for CA_Center in CA_Centers:
Layers =
m.listLayers("CumulativeSumWithin{0}_{1}_Jun2018".format(Market,CA_Center))
fields = ['SUM_USER_VisitCount']
for Layer in Layers:
print(Layer)
sqlClause = (None, 'ORDER BY ' + 'SUM_USER_VisitCount') # + 'DESC'
with arcpy.da.SearchCursor(in_table = Layer, field_names = fields,
sql_clause = sqlClause) as searchCursor:
print (max(searchCursor))
You can create a dictonary that stores the results from each query and then print out the highest one at the end.
results_dict = {}
for Market in Markets:
print(Market)
for CA_Center in CA_Centers:
Layers =
m.listLayers("CumulativeSumWithin{0}_{1}_Jun2018".format(Market,CA_Center))
fields = ['SUM_USER_VisitCount']
for Layer in Layers:
print(Layer)
sqlClause = (None, 'ORDER BY ' + 'SUM_USER_VisitCount') # + 'DESC'
with arcpy.da.SearchCursor(in_table = Layer, field_names = fields,
sql_clause = sqlClause) as searchCursor:
print (max(searchCursor))
results_dict[Layer] = max(searchCursor)
# get key for dictionary item with the highest value
highest_count_layer = max(results_dict, key=results_dict.get)
print(highest_count_layer)
print(results_dict[highest_count_layer])

Geoviews points: changing colormap with high and low options

I recently looked at this question on manually setting the limits of a holoviews colorbar, but after changing the range on one of my vdims, it didn't change the high and low limits of the colorbar. Is there a way to pass a Bokeh LinearColorMapper (and its options) directly for a particular vdim?
opts = {'plot' : dict(width=width_val, height=height_val, tools=[hover_shipments],
size_index='po_qty',
color_index='magnitude',
size_fn=(lambda x : x/100),
click_policy='hide', colorbar=True),
'style': dict(cmap='Viridis', line_width=0.25, alpha=0.75, fill_alpha=0.75,
muted_alpha=0.05)}
ds_time_store.to(gv.Points,
kdims=['longitude_qty','latitude_qty'],
vdims=['store_num',
'city_nm',
'po_qty',
hv.Dimension('magnitude', range=(0, 50))], label='late').opts({'Points' : opts})
By calling redim(aggregate_rating=dict(range=(0, 5))) on my data set locality_ratings before setting up the Points, I was able to set the boundaries for the colorbar from 0 to 5 as per my ratings.
points = locality_ratings.redim(aggregate_rating=dict(range=(0, 5))).to(gv.Points, ['longitude', 'latitude'],
['aggregate_rating', 'votes', 'cuisine_count', 'average_cost_for_two', 'price_range', 'locality'])
(gts.Wikipedia * points.options(width=700, height=600,
tools=['hover', 'save', 'zoom_in', 'zoom_out', 'pan' , 'wheel_zoom'],
colorbar=True, toolbar='above', xaxis=None, yaxis=None,
size_index=3, color_index=2, size=3, cmap=bokeh.palettes.all_palettes['Dark2'][5])).redim(longitude="Longitude",
latitude="Latitude",
aggregate_rating='Rating',
locality="Locality",
votes="Votes",
price_range="Price Range",
average_cost_for_two="Avg. Cost for 2 (R)",
cuisine_count="No. Cuisines"
)

Plotting multiple states bokeh

I'm trying to plot two things:
Counties for MD, VA, and DC
Lats/Longs for housing listings in that area (most expensive in a certain color
and least expensive in another color)
However, I'm having trouble with part 1, and cannot seem to plot the counties without getting the error message:
"Javascript error adding output!
Error: Error rendering Bokeh model: could not find tag with id: xxxxxxxxxxx
See your browser Javascript console for more details."
where xxxxx are numbers
from bokeh.io import show
from bokeh.models import (
ColumnDataSource,
HoverTool,
LogColorMapper)
from bokeh.palettes import Viridis6 as palette
from bokeh.plotting import figure
from bokeh.sampledata.us_counties import data as counties
from bokeh.sampledata.unemployment import data as unemployment
palette.reverse()
va_counties = {
code: county for code, county in counties.items() if county["state"] == "va"
}
md_counties = {
code: county for code, county in counties.items() if county["state"] == "md"
}
dc_counties = {
code: county for code, county in counties.items() if county["state"] == "dc"
}
va_county_xs = [county["lons"] for county in va_counties.values()]
va_county_ys = [county["lats"] for county in va_counties.values()]
md_county_xs = [county["lons"] for county in md_counties.values()]
md_county_ys = [county["lats"] for county in md_counties.values()]
dc_county_xs = [county["lons"] for county in dc_counties.values()]
dc_county_ys = [county["lats"] for county in dc_counties.values()]
va_county_names = [county['name'] for county in va_counties.values()]
md_county_names = [county['name'] for county in md_counties.values()]
dc_county_names = [county['name'] for county in dc_counties.values()]
#county_rates = [unemployment[county_id] for county_id in counties]
color_mapper = LogColorMapper(palette=palette)
va_source = ColumnDataSource(data=dict(
x=va_county_xs,
y=va_county_ys,
name=va_county_names,
))
md_source = ColumnDataSource(data=dict(
x=md_county_xs,
y=md_county_ys,
name=md_county_names,
))
dc_source = ColumnDataSource(data=dict(
x=dc_county_xs,
y=dc_county_ys,
name=dc_county_names,
))
TOOLS = "pan,wheel_zoom,reset,hover,save"
va = figure(
title="Texas Unemployment, 2009", tools=TOOLS,
x_axis_location=None, y_axis_location=None
)
va.grid.grid_line_color = None
md = figure(
title="Texas Unemployment, 2009", tools=TOOLS,
x_axis_location=None, y_axis_location=None
)
md.grid.grid_line_color = None
dc = figure(
title="Texas Unemployment, 2009", tools=TOOLS,
x_axis_location=None, y_axis_location=None
)
dc.grid.grid_line_color = None
va.patches('x', 'y', source=va_source,
fill_color={'field': 'rate', 'transform': color_mapper},
fill_alpha=0.7, line_color="white", line_width=0.5)
md.patches('x', 'y', source=md_source,
fill_color={'field': 'rate', 'transform': color_mapper},
fill_alpha=0.7, line_color="white", line_width=0.5)
dc.patches('x', 'y', source=dc_source,
fill_color={'field': 'rate', 'transform': color_mapper},
fill_alpha=0.7, line_color="white", line_width=0.5)
hover = p.select_one(HoverTool)
hover.point_policy = "follow_mouse"
hover.tooltips = [
("Name", "#name"),
("(Long, Lat)", "($x, $y)"),
]
show(va)
show(md)
show(dc)
Bokeh maintains an implicit "current document" and by default everything you make gets added to that. This makes it very simple to have a script that generates one HTML file, and especially makes usage in the Jupyter notebook much more simple and transparent. In general this is a net positive, but it does make certain other usage patterns need to be slightly more verbose. In particular in your case with multiple show calls, each call to show gets the same document which is probably not what you intend. The solution is to create and show each plot in order, and call reset_output in between. Additionally, you would really need to specify unique filenames for each separate output, by using output_file. Here is a small complete example:
from bokeh.io import output_file, reset_output, show
from bokeh.plotting import figure
# create and show one figure
p1 = figure(title="plot 1")
p1.circle([1,2,3], [4,6,5])
output_file("p1.html")
show(p1)
# clear out the "current document"
reset_output()
# create and show another figure
p2 = figure(title="plot 2")
p2.circle([1,2,3], [8,6,7])
output_file("p2.html")
show(p2)
There are other ways to do this by managing Bokeh Document objects explicitly yourself, but I would probably say this is the simplest to get started.

rdlc background color bug - large expression seems to cause a bug

I am working on designing a rather large rdlc report in ASP.Net MS visual 2010. Some rows in the report require the row to be highlighted if something is out of place. So I went to the background colors tab in the Properties box of my rdlc report after clicking on the table row. I am trying to get the following expression to work in the background color tab in the properties box.
`=IiF((Fields!C.Value < .75 And Fields!C.Value <> "")
Or (Fields!S.Value < .75 And Fields!S.Value <> "")
Or (Fields!O.Value > 5), "Yellow", "White")`
Originally I want the background color either yellow or white, but for testing purposes I changed white to green since white is a default it seems.
`=IiF((Fields!C.Value < .75 And Fields!C.Value <> "")
Or (Fields!S.Value < .75 And Fields!S.Value <> "")
Or (Fields!O.Value > 5), "Yellow", "Green")`
This caused some rows to be green, but none were yellow, the rows that should be yellow are instead white.
It works fine when I shorten it to
`=IiF((Fields!C.Value < .75 ), "Yellow", "Green")`
I get all Green and Yellow rows.
And it worked fine when I tried
`=IiF((Fields!C.Value < .75 And Fields!C.Value <> ""), "Yellow", "Green")
This worked fine too I get all rows being either Green or Yellow.
But as soon as I add an Or they stop working.
`=IiF((Fields!C.Value < .75 And Fields!C.Value <> "")
Or Fields!O.Value > 5 , "Yellow", "Green")`
This results in some Green rows but no yellow rows, the should be yellow rows all come out white?
And in some cases I get no Green or Yellow rows. I tired in versing the original statement,
`IiF((Fields!Cpk_C.Value >= .75 Or Fields!Cpk_C.Value = "")
And (Fields!Cpk_S.Value >= .75 Or Fields!Cpk_S.Value = "")
And (Fields!Cpk_S.Value <= 5), "Green", "Yellow")`
but then nothing works as it's all white rows.
Any help in what I am doing wrong, or why this doesn't work, is appreciated, thanks.
As shown in the comments above the problem was solved (thanks to a tip from Ic). The issue had to do with the type of values the items C.Value and S.Value. They were Decimal based and not string so a comparison to <> "" was causing a format warning which wouldn't execute the code on those rows resulting a no color applied as a result. Since they were essentially floats the IsNumeric function was a better fit.
=IiF((Fields!Cpk_C.Value > .75 And IsNumeric(Fields!Cpk_C.Value)) Or (Fields!Cpk_S.Value > .75 And IsNumeric(Fields!Cpk_S.Value)) Or Fields!OOC.Value > 5, "Yellow", "White")

Resources