ipywidgets dropdown with pandas MultiIndex - drop-down-menu

How can the ipywidgets dropdown menu be used with a pandas MultiIndex as the options field? It seems to display only the first level from the MultiIndex. For example, the following code run in JupyterLab only shows options [1, 1, 2, 2].
import ipywidgets
import pandas as pd
arrays = [[1, 1, 2, 2], ['red', 'blue', 'red', 'blue']]
index = pd.MultiIndex.from_arrays(arrays, names=('number', 'color'))
dropdown = ipywidgets.Dropdown(options=index)
display(dropdown)

Related

How to not show repeated values in a heatmap in plotly express (px.imshow)?

I'm trying to plot a matrix using a heatmap chart but I would like to avoid repeated values;
When using seaborn we can set a "mask" to avoid showing all values, but I can't find the equivalent on Plotly / Plotly Express;
I would like to see something like:
But at this moment, it is the below format:
Below is an MWE example of my data structure... Any reference or help to do this will be very welcome
import pandas as pd
import plotly.express as px
heatmap_data=pd.DataFrame(
{'user1': {'user1': 1,
'user2': 0.5267109866774764,
'user3': 0.905914413030722},
'user2': {'user1': 0.5267109866774764,
'user2': 1,
'user3': 0.5160264783692895},
'user3': {'user1': 0.905914413030722,
'user2': 0.5160264783692895,
'user3': 1}
})
fig = px.imshow(heatmap_data, zmin=0, zmax=1,
text_auto=True,
color_continuous_scale="Plasma")
fig
Thank you in advantage
The plotly heatmap does not implement the functionality you would expect. Also, matrix diagrams such as scatter plots have the ability to hide the top half. See this for examples. So I take advantage of the fact that null values are not displayed and replace unwanted data with null values in the original data. The default style then remains, so we change the theme and hide the axis lines. Finally, the height of the color bar is adjusted.
import pandas as pd
import plotly.express as px
heatmap_data=pd.DataFrame(
{'user1': {'user1': 1,
'user2': 0.5267109866774764,
'user3': 0.905914413030722},
'user2': {'user1': 0.5267109866774764,
'user2': 1,
'user3': 0.5160264783692895},
'user3': {'user1': 0.905914413030722,
'user2': 0.5160264783692895,
'user3': 1}
})
heatmap_data.loc['user1','user2']=None
heatmap_data.loc['user1','user3']=None
heatmap_data.loc['user2','user3']=None
fig = px.imshow(heatmap_data,
zmin=0,
zmax=1,
text_auto=True,
color_continuous_scale="Plasma",
template='simple_white'
)
fig.update_xaxes(showline=False)
fig.update_yaxes(showline=False)
fig.update_layout(autosize=False, width=400, coloraxis=dict(colorbar=dict(len=0.8)))
fig

How to add control for single subplot in plotly?

In plotly I use a figure that contains several subplot.
For the last subplot I want to be able to change the type with a dropdown menu.
However, the "restyle" action of the dropdown seems to be applied to the whole figure?
If I use the dropdown, the other subplots disapear:
=> How to add a plotly control for a specific subplot?
or
=> How to tell a control do only influence the properties of a specific subplot?
Read data
import pandas as pd
​
# read in volcano database data
df = pd.read_csv(
"https://raw.githubusercontent.com/plotly/datasets/master/volcano_db.csv",
encoding="iso-8859-1",
)
​
# frequency of Country
freq = df
freq = freq.Country.value_counts().reset_index().rename(columns={"index": "x"})
​
# read in 3d volcano surface data
df_v = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/volcano.csv")
Initialize figure with subplots
from plotly.subplots import make_subplots
import plotly.graph_objects as go
fig = make_subplots(
rows=3,
cols=2,
column_widths=[0.6, 0.4],
row_heights=[0.4, 0.2, 0.4],
specs=[
[{"type": "scattergeo", "rowspan": 2}, {"type": "bar"}],
[None, None],
[None, {"type": "surface"}]
]
)
# Add scattergeo globe map of volcano locations
scatter_geo = go.Scattergeo(
lat=df["Latitude"],
lon=df["Longitude"],
mode="markers",
hoverinfo="text",
showlegend=False,
marker=dict(color="crimson", size=4, opacity=0.8)
)
fig.add_trace(
scatter_geo,
row=1,
col=1
)
# Add locations bar chart
bar = go.Bar(
x=freq["x"][0:10],
y=freq["Country"][0:10],
marker=dict(color="crimson"),
showlegend=False
)
fig.add_trace(
bar,
row=1,
col=2
)
# Add 3d surface of volcano
surface_3d = go.Surface(
z=df_v.values.tolist(),
showscale=False
)
fig.add_trace(
surface_3d,
row=3,
col=2
)
fig
Add controls
# Add dropdown
updatemenu = dict(
buttons=list([
dict(
args=["type", "surface"],
label="3D Surface",
method="restyle"
),
dict(
args=["type", "heatmap"],
label="Heatmap",
method="restyle"
)
]),
direction="down",
pad={"r": 10, "t": 10},
showactive=True,
x=1,
y=0.4
)
fig['layout'].update(
updatemenus=[{}, {}, {}, {}, {}, updatemenu]
)
#Add slider
steps = []
for i in range(10):
step = dict(
method="update",
args=[{"title": "Slider switched to step: " + str(i)}], # layout attribute
)
steps.append(step)
slider = dict(
active=10,
currentvalue={"prefix": "Frequency: "},
pad={"t": 50},
steps=steps
)
fig.update_layout(
sliders=[slider]
)
Additional styling
# Update geo subplot properties
fig.update_geos(
projection_type="orthographic",
landcolor="white",
oceancolor="MidnightBlue",
showocean=True,
lakecolor="LightBlue"
)
# Rotate x-axis labels
fig.update_xaxes(tickangle=45)
# Set theme, margin, and annotation in layout
fig.update_layout(
autosize=False,
width=800,
height=500,
template="plotly_dark",
margin=dict(r=10, t=25, b=40, l=60),
scene_camera_eye=dict(x=2, y=2, z=0.3),
annotations=[
dict(
text="Source: NOAA",
showarrow=False,
xref="paper",
yref="paper",
x=0,
y=0)
]
)
fig.show()
Unfortunately, this is not a complete answer. But hopefully, what I'm about to show you will help you on your way. You see, you can specify which subplot to edit by the traces contained in that subplot. You do so by adding an integer in args() like so:
buttons=list([
dict(
args=["type", "surface", [2]],
label="3D Surface",
method="restyle"
)
And [2] references the position of your trace in fig.data:
(Scattergeo({
'geo': 'geo',
'hoverinfo': 'text',
'lat': array([ 34.5 , -23.3 , 14.501, ..., 15.05 , 14.02 , 34.8 ]),
'lon': array([ 131.6 , -67.62 , -90.876, ..., 42.18 , 42.75 , -108. ]),
'marker': {'color': 'crimson', 'opacity': 0.8, 'size': 4},
'mode': 'markers',
'showlegend': False
}),
Bar({
'marker': {'color': 'crimson'},
'showlegend': False,
'x': array(['United States', 'Russia', 'Indonesia', 'Japan', 'Chile', 'Ethiopia',
'Papua New Guinea', 'Philippines', 'Mexico', 'Iceland'], dtype=object),
'xaxis': 'x',
'y': array([184, 169, 136, 111, 87, 57, 54, 49, 41, 38], dtype=int64),
'yaxis': 'y'
}),
Surface({
'scene': 'scene',
'showscale': False,
The problem is, that doing it this way in your case will trigger some very peculiar behavior: when the button is set to heatmap, the data becomes bart of the Bar figure:
And what's even stranger, is that it looks the way it should when you select 3D Surface again:
And I honestly have no idea what causes this. Take a look for yourself in the complete code snippet below and see what you can make of it. Maybe we'll be able to figure it out eventually...
Complete code:
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import pandas as pd
# read in volcano database data
df = pd.read_csv(
"https://raw.githubusercontent.com/plotly/datasets/master/volcano_db.csv",
encoding="iso-8859-1",
)
# frequency of Country
freq = df
freq = freq.Country.value_counts().reset_index().rename(columns={"index": "x"})
# read in 3d volcano surface data
df_v = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/volcano.csv")
df_v
fig = make_subplots(
rows=3,
cols=2,
column_widths=[0.6, 0.4],
row_heights=[0.4, 0.2, 0.4],
specs=[
[{"type": "scattergeo", "rowspan": 2}, {"type": "bar"}],
[None, None],
[None, {"type": "surface"}]
]
)
# Add scattergeo globe map of volcano locations
scatter_geo = go.Scattergeo(
lat=df["Latitude"],
lon=df["Longitude"],
mode="markers",
hoverinfo="text",
showlegend=False,
marker=dict(color="crimson", size=4, opacity=0.8)
)
fig.add_trace(
scatter_geo,
row=1,
col=1
)
# Add locations bar chart
bar = go.Bar(
x=freq["x"][0:10],
y=freq["Country"][0:10],
marker=dict(color="crimson"),
showlegend=False
)
fig.add_trace(
bar,
row=1,
col=2
)
# Add 3d surface of volcano
surface_3d = go.Surface(
z=df_v.values.tolist(),
showscale=False
)
fig.add_trace(
surface_3d,
row=3,
col=2
)
# Add dropdown
updatemenu = dict(
buttons=list([
dict(
args=["type", "surface", [2]],
label="3D Surface",
method="restyle"
),
dict(
args=["type", "heatmap", [2]],
label="Heatmap",
method="restyle"
)
]),
direction="down",
pad={"r": 10, "t": 10},
showactive=True,
x=1,
y=0.4
)
fig['layout'].update(
updatemenus=[{}, {}, {}, {}, {}, updatemenu]
)
#Add slider
steps = []
for i in range(10):
step = dict(
method="update",
args=[{"title": "Slider switched to step: " + str(i)}], # layout attribute
)
steps.append(step)
slider = dict(
active=10,
currentvalue={"prefix": "Frequency: "},
pad={"t": 50},
steps=steps
)
fig.update_layout(
sliders=[slider]
)
# Update geo subplot properties
fig.update_geos(
projection_type="orthographic",
landcolor="white",
oceancolor="MidnightBlue",
showocean=True,
lakecolor="LightBlue"
)
# Rotate x-axis labels
fig.update_xaxes(tickangle=45)
# Set theme, margin, and annotation in layout
fig.update_layout(
autosize=False,
width=800,
height=500,
template="plotly_dark",
margin=dict(r=10, t=25, b=40, l=60),
scene_camera_eye=dict(x=2, y=2, z=0.3),
annotations=[
dict(
text="Source: NOAA",
showarrow=False,
xref="paper",
yref="paper",
x=0,
y=0)
]
)
fig.show()

When using rasterize=True with datashader, how do I get transparency where count=0 to see the underlying tile?

Currently, when I do this:
import pandas as pd
import hvplot.pandas
df = pd.util.testing.makeDataFrame()
plot = df.hvplot.points('A', 'B', tiles=True, rasterize=True, geo=True,
aggregator='count')
I can't see the underlying tile source.
To see the underlying tile source philippjfr suggested setting the color bar limits slightly higher than 0 and set the min clipping_colors to transparent:
plot = plot.redim.range(**{'Count': (0.25, 1)})
plot = plot.opts('Image', clipping_colors={'min': 'transparent'})
Now the underlying tile source is viewable.
Full Code:
import pandas as pd
import hvplot.pandas
df = pd.util.testing.makeDataFrame()
plot = df.hvplot.points('A', 'B', tiles=True, rasterize=True, geo=True,
aggregator='count')
plot = plot.redim.range(**{'Count': (0.25, 1)})
plot = plot.opts('Image', clipping_colors={'min': 'transparent'})
plot

Trying to create image from appended array

I have a list of images in a directory. I am trying to extract a column from each image (image size is 403 px by 1288 px by 3 bands) , and sequentially build an array from these columns using numpy append that I want to save as an image. I'm trying to use numpy and pillow to make an image from this appended array.
I have researched Pillor, Numpy documentation
# !/usr/bin/python3
import numpy as np
from numpy import array
from PIL import Image
import os, time, sys, subprocess
savpath =
'C:/data/marsobot/spectral/pushbroom/zwoexperiments/fullsuntheframes/'
os.chdir('C:/data/marsobot/spectral/pushbroom/zwoexperiments/fullsuntheframes/')
toappendarr = np.empty ([403, 1288, 3])
for root, dirs, files in os.walk(".", topdown = False):
for name in files:
img = Image.open(name)
arr = array(img)
value = arr[:, 300, 1]
toappendarr = np.append(toappendarr, value, axis=1)
print(toappendarr.shape)
imgout = Image.fromarray(arr)
imgout.save("output.jpg")
I expected an image but instead I got:
ValueError: all the input arrays must have same number of dimensions

ultimo theme brand slider dont work

I have Magento with Ultimo Theme
I have Set Up the Brand Slider on Home Page
It shows 4 Brands with images. I have 6 Brands. Only the first 4 ore shown
and it doesnt slider to the other
Have anyone an idea?
Here is my code:
{{block type=”brands/brands” template=”infortis/brands/brand_slider.phtml” breakpoints=”[0, 1], [320, 2], [480, 2], [768, 3], [960, 4], [1280, 5]” move=”1″ pagination=”1″ block_name=”Our Brands”}}
You must add "brands/brands" to System-Permissions-Blocks
Same issue here.
<div class="col-md-12" class="our_brands_block" style="background-color: #f0f2fb;>
{{block class="Infortis\Brands\Block\Brands" template="brand_slider.phtml" breakpoints="[0, 1], [320, 2], [480, 2], [768, 5], [960, 6], [1280, 6]" move=1 loop=1 timeout=1000 speed=500 pagination=1}}
</div>
Add the content above as a CMS block.
Configure a widget as.
Page: CMS Pages (All)
Container: Postscript, Full Width
This adds it full width just above the footer area.
But lazy load does not appear to work and animation is not working.
Magento 2.3.0

Resources