I am trying to change the font size of a caption using the pandas styling API. Is this possible?
Here is what I have so far:
import pandas as pd
data = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=data)
df.style.set_caption("Some Caption")
Appreciate any input.
Try this:
df.style.set_caption("Some Caption").set_table_styles([{
'selector': 'caption',
'props': [
('color', 'red'),
('font-size', '16px')
]
}])
Related
I have time series data recorded at discrete ordinal levels (e.g. 0, 1, 2), and I'd like to plot them with meaningful names (e.g. low, medium, high).
Currently I have:
import pandas as pd
import plotly.express as px
df = pd.DataFrame({
"x": ["2022-01-01", "2022-01-02", "2022-01-03", "2022-01-04"],
"y": [2, 1, 2, 0],
})
fig = px.line(x=df.x, y=df.y, line_shape="hv")
fig.show()
which produces:
But I'd like something like:
This feels like the easiest way:
import pandas as pd
import plotly.express as px
df = pd.DataFrame({
"x": ["2022-01-01", "2022-01-02", "2022-01-03", "2022-01-04"],
"y": [2, 1, 2, 0],
})
fig = px.line(x=df.x, y=df.y, line_shape="hv")
fig.update_yaxes(
ticktext=["Low", "Medium", "High"],
tickvals=[0, 1, 2],
)
fig.show()
Result:
In Plotly language this falls under the "categorical" umbrella.
If the order needs tweaked, the categoryarray and categoryorder can also be set with update_yaxes.
https://plotly.com/python/reference/layout/yaxis/#layout-yaxis-categoryarray
https://plotly.com/python/reference/layout/yaxis/#layout-yaxis-categoryorder
I have a dataframe:
import pandas as pd
import numpy as np
df = pd.DataFrame(
data={'X': [1.5, 6.777, 2.444, np.NaN],
'Y': [1.111, np.NaN, 8.77, np.NaN],
'Z': [5.0, 2.333, 10, 6.6666]})
I think this should work, but i get the following error;
df.at[1,'Z'] =(df.loc[[2],'X'] +df.loc[[0],'Y'])
How can I achieve this?
ValueError: setting an array element with a sequence.
This should work
df.loc[1, 'Z'] = df.loc[2,'X'] + df.loc[0,'Y']
Does anyone know if it is possible to specify a mapping that varies the size of markers in a Plotly scattermapbox visualization as one varies the zoom level? I'd like to layer a scattermapbox visualization over a densitymapbox visualization and have the scatter plot be invisible at larger scales but come into view as one zooms in.
Thanks!
you can specify minzoom on layers
below example shows a density mapbox that are replaced by red markers after zooming in past zoom 4
this clearly works where markers and density items are the same. If different, best that you update question with sample data
import plotly.express as px
import pandas as pd
import geopandas as gpd
import shapely.geometry
import json
df = pd.DataFrame(
data=(
[
[32.4087249155, -100.9509696428, "2013-01-01", 1],
[31.5201976084, -102.1030942593, "2013-01-01", 1],
[31.434573418, -102.0592907601, "2013-01-01", 1],
[31.2635930582, -101.95341361, "2013-01-01", 1],
[31.4287233847, -102.0253840388, "2013-01-01", 1],
[31.4872286706, -101.5455598032, "2021-01-01", 1],
[31.5439162579, -101.4833865708, "2021-01-01", 1],
[31.5439362581, -101.4833065695, "2021-01-01", 1],
[31.7980713977, -102.0937650441, "2021-01-01", 1],
[32.02050082, -103.31736372, "2021-01-01", 1],
]
),
columns=["Latitude", "Longitude", "Date", "Count"],
)
fig = px.density_mapbox(
df,
lat="Latitude",
lon="Longitude",
z="Count",
radius=10,
zoom=3,
)
# fig = go.Figure(go.Scattermapbox())
fig.update_layout(
mapbox_layers=[
{
# "below": "traces",
"circle": {"radius": 10},
"color":"red",
"minzoom": 4,
"source": gpd.GeoSeries(
df.loc[:, ["Longitude", "Latitude"]].apply(
shapely.geometry.Point, axis=1
)
).__geo_interface__,
},
],
mapbox_style="carto-positron",
)
data = {
'X': [3, 2, 0, 1],
'Y': [0, 3, 7, 2]
}
df = pd.DataFrame(data, index=['A', 'B', 'C', 'D'])
df.style.set_properties(**{
'font-family':'Courier New'
})
df
The index column is displayed in bold, is it possible to change font of index column?
You must use table_styles. In this example I manage to make the "font-weight":"normal" for the index and columns:
Let's define some test data:
import pandas as pd
df = pd.DataFrame({'A':[1,2,3,4],
'B':[5,4,3,1]})
We define style customization to use:
styles = [
dict(selector="th", props=[("font-weight","normal"),
("text-align", "center")])]
We pass the style variable as the argument for set_table_styles():
html = (df.style.set_table_styles(styles))
html
And the output is:
Please feel free to read about the documentation in pandas Styling for more details.
I am trying to do a scatter plot with pandas. Unfortunately kind='scatter' doesn't work. If I change this to kind='line' it works as expected. What can I do to fix this?
for label, d in df.groupby('m'):
d[['te','n']].sort_values(by='n', ascending=False).plot(kind="scatter", x='n', y='te', ax=ax, label='m = '+str(label))```
Use plot.scatter instead:
df = pd.DataFrame({'x': [0, 5, 7,3, 2, 4, 6], 'y': [0, 5, 7,3, 2, 4, 6]})
df.plot.scatter('x', 'y')
Use this snippet if you want individual labels and colours:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({
'm': np.random.randint(0, 5, size=100),
'x': np.random.uniform(size=100),
'y': np.random.uniform(size=100),
})
fig, ax = plt.subplots()
for label, d in df.groupby('m'):
# generate a random color:
color = list(np.random.uniform(size=3))
d.plot.scatter('x', 'y', label=f'group {label}', ax=ax, c=[color])