I'm new to the method. I created the following input, but it gives me an empty output. What did I miss? Thank you.
import pandas as pd
from bokeh.charts import Bar
import pandas as pd
from bokeh.plotting import figure, output_file, show
mortality_age = pd.read_csv("mortality_by_age.csv")
x=mortality_age["Age Range"]
y=mortality_age["Deaths per 100,000 Live Births:"]
plot = figure(title="Example of a vertical bar chart")
plot.vbar(x, top=y, width=0.5,color="#CAB2D6")
output_file("vertical_bar.html", mode="inline")
show(plot)
what version of Bokeh are you using?
Using 12.10, I have managed to get a plot to show using the code below, using the example contained in the documentation.
# import pandas as pd
from bokeh.plotting import figure, output_file, show
# from bokeh.charts import Bar # I had issues with this line working
# mortality_age = pd.read_csv("mortality_by_age.csv")
# x=mortality_age["Age Range"]
# y=mortality_age["Deaths per 100,000 Live Births:"]
x=[1, 2, 3, 4, 5]
y=[6, 7, 6, 4, 5]
plot = figure(title="Example of a vertical bar chart")
plot.vbar(x=[1, 2, 3, 4, 5], top=y, width=0.5, color="#CAB2D6")
output_file("vertical_bar.html", mode="inline")
show(plot)
My recommendations would be to check the version of bokeh you are using, and then check the data contained in your csv file, it might be possible there is nothing in there.
Related
I was wondering if it is possible to make my colorscale bar ascending (from 1 to 4) instead of descending (from 4 to 1). Does anyone have clue? The picture of my current bar is underneath the code.
import pandas as pd
import plotly.graph_objects as go
fig = go.Figure(go.Densitymapbox(lat=df_dropped.latitude, lon=df_dropped.longitude, z=df_dropped.propextent,
radius=10))
fig.update_layout(mapbox_style="stamen-terrain", mapbox_center_lon=180)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()
Just add reversescale=True as below:
import pandas as pd
import plotly.graph_objects as go
fig = go.Figure(go.Densitymapbox(lat=df_dropped.latitude,
lon=df_dropped.longitude, z=df_dropped.propextent,radius=10,reversescale=True
))
fig.update_layout(mapbox_style="stamen-terrain", mapbox_center_lon=180)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()
For more details, please visit the reversescale section in the documentation
I'm using holoviews with bokeh backend for interactive visualizations. I have a histogram with edges and frequency data. What is an elegant way of overlaying my histogram with the cumulative distribution (cdf) curve?
I tried using the cumsum option in hv.dim but don't think i'm doing it right. The help simply says,
Help on function cumsum in module holoviews.util.transform:
cumsum(self, **kwargs)
My code looks something like,
df_hist = pd.DataFrame(columns=['edges', 'freq'])
df_hist['edges'] = [-2, -1, 0, 1, 2]
df_hist['freq'] = [1, 3, 5, 3, 1]
hv.Histogram((df_hist.edges, df_hist.freq))
The result is a histogram plot.
Is there something like a...
hv.Histogram((df_hist.edges, df_hist.freq), type='cdf')
... to show the cumulative distribution?
One possible solution is by using histogram(cumulative=True) as follows:
from holoviews.operation import histogram
histogram(hv.Histogram((df_hist.edges, df_hist.freq)), cumulative=True)
More info on transforming elements here:
http://holoviews.org/user_guide/Transforming_Elements.html
Or a more general solution by turning the original data into a hv.Dataset():
import holoviews as hv
import seaborn as sns
hv.extension('bokeh')
iris = sns.load_dataset('iris')
hv_data = hv.Dataset(iris['petal_width'])
histogram(hv_data, cumulative=True)
But I like using library hvplot, which is built on top of Holoviews, even more:
import hvplot
import hvplot.pandas
iris['petal_width'].hvplot.hist(cumulative=True)
I am trying to update the data source for a Bokeh scatter plot using a function.
But instead of plotting only the new data, the plot shows all of it.
I think I'm passing a new data source to the plot, but the old plotted points persist.
How would you update the scatterplot with just new data?
Also, is there any way of retrieving the current selection in the dropdown menu without interacting with it? (i.e. without a callback that uses on_change)
import numpy as np
import pandas as pd
from bokeh.models import ColumnDataSource
from bokeh.models.widgets import Tabs, Select
from bokeh.layouts import column, row, Spacer
from bokeh.io import curdoc
from bokeh.plotting import figure, curdoc, show
#Plotting points on initial chart.
df_AB = pd.DataFrame(np.random.randint(0,100,size=(500, 2)), columns=list('AB'), index=[str(i) for i in range(1,500+1)])
pointchart=figure(plot_width=800, plot_height=700, tools=['lasso_select','box_select'],title="Point scatter")
pointchart_source= ColumnDataSource(df_AB[["A","B"]])
pointchart_glyph= pointchart.circle("A","B",source=pointchart_source)
#Dropdown
selectoroptions=['','new selection', 'other selection']
Xselector = Select(title="Dropdown:", value="", options=selectoroptions)
#Callback to update data source
def Xdropdownchange(attrname, old, new):
pointchart_glyph= pointchart.circle("X","Y",source=make_updated_source())
Xselector.on_change("value", Xdropdownchange)
#Making new/updated data source based on dropdowns.
df_XY = pd.DataFrame(np.random.randint(0,100,size=(500, 2)), columns=list('XY'), index=[str(i) for i in range(1,500+1)])
def make_updated_source():
new_x=pd.Series(list(df_XY.iloc[0:100]["X"]),name="X")
new_y=pd.Series(list(df_XY.iloc[0:100]["Y"]),name="Y")
sourcedf=pd.DataFrame([new_x,new_y]).T
pointchart_source= ColumnDataSource(sourcedf)
return pointchart_source
#Show
layout=row(column(Xselector, Spacer(width=400, height=500)),pointchart)
curdoc().add_root(layout)
!powershell -command {'bokeh serve --show Dropdown_sourcechange.ipynb'}
I changed some things in your code and it now shows your original data if you select the empty value in your dropdown or a randomly generated dataset when you select one of the other values in the dropdown. Retrieving the current selection in the dropdown without using a callback is also possible with print(Xselector.value)
import numpy as np
import pandas as pd
from bokeh.models import ColumnDataSource
from bokeh.models.widgets import Tabs, Select
from bokeh.layouts import column, row, Spacer
from bokeh.io import curdoc
from bokeh.plotting import figure, curdoc, show
#Plotting points on initial chart.
df_AB = pd.DataFrame(np.random.randint(0,100,size=(500, 2)), columns=list('XY'), index=[str(i) for i in range(1,500+1)])
pointchart=figure(plot_width=800, plot_height=700, tools=['lasso_select','box_select','wheel_zoom'],title="Point scatter")
source= ColumnDataSource(df_AB[["X","Y"]])
pointchart.circle("X","Y",source=source)
#Dropdown
selectoroptions=['','new selection', 'other selection']
Xselector = Select(title="Dropdown:", value="", options=selectoroptions)
def make_updated_source(attr, old, new):
if new == '':
source.data = ColumnDataSource(df_AB[["X","Y"]]).data
else:
df_XY = pd.DataFrame(np.random.randint(0,100,size=(500, 2)), columns=list('XY'), index=[str(i) for i in range(1,500+1)])
new_x=pd.Series(list(df_XY.iloc[0:100]["X"]),name="X")
new_y=pd.Series(list(df_XY.iloc[0:100]["Y"]),name="Y")
sourcedf=pd.DataFrame([new_x,new_y]).T
source.data = ColumnDataSource(sourcedf).data
Xselector.on_change("value", make_updated_source)
#Retrieve selection in dropdown withoud on_change
print(Xselector.value)
#Show
layout=row(column(Xselector, Spacer(width=400, height=500)),pointchart)
curdoc().add_root(layout)
!powershell -command {'bokeh serve --show Dropdown_sourcechange.ipynb'}
I could not find the information regarding the helptool on the bokeh documentation. There is an explanation for all other tools but not this one. I am talking about these tools from the toolbar:
http://docs.bokeh.org/en/latest/docs/user_guide/tools.html
I can choose most of the plot tools I want to use with no problem. I want to include the helptool, which is clearly visible just before the bokeh logo, however I cannot find any direct reference to it.
I just tested it(!), if you want the Helptool, which has a "?" sybmol, it will only be included by default if you do not specify the tools displayed with the plot. OK I will go with this but I will have no "?" if I choose the tools.
I understand your problem I think. You are saying that by default the tool panel will include the help tool. When you specify all the tools from scratch, help tool is not included as default.
If you generate the plot without specifying any tools, then list all tools on the plot:
p.tools
>>>>
[PanTool(id='450f2e26-e0e5-4d90-89c4-44d20f2f688b', ...),
WheelZoomTool(id='84011ce1-4f73-4abb-abd1-26a830b70635', ...),
BoxZoomTool(id='adbfb29a-aa7d-4883-8f8f-d12b7c5af139', ...),
SaveTool(id='ff6ba8bb-c487-418d-82e5-28ff0402e2d6', ...),
ResetTool(id='dfac2559-da4c-4902-829d-f795ee0bfd56', ...),
HelpTool(id='1141330c-e9ff-4e5b-a737-3517c24f263e', ...)]
so you can see there is a helptool. Also it is in the documents
http://docs.bokeh.org/en/latest/docs/reference/models/tools.html#bokeh.models.tools.HelpTool
Therefore you can import this tool and add it to the plot in two ways:
from bokeh.plotting import figure, output_file, show
from bokeh.models import HelpTool
output_file("toolbar.html")
# create a new plot with the toolbar below
p = figure(plot_width=400, plot_height=400,
title=None, toolbar_location="below", tools="pan,wheel_zoom,box_zoom,reset")
p.add_tools(HelpTool())
p.circle([1, 2, 3, 4, 5], [2, 5, 8, 2, 7], size=10)
show(p)
Or more simply:
from bokeh.plotting import figure, output_file, show
output_file("toolbar.html")
# create a new plot with the toolbar below
p = figure(plot_width=400, plot_height=400,
title=None, toolbar_location="right",tools = "pan,wheel_zoom,box_zoom,reset,help")
p.circle([1, 2, 3, 4, 5], [2, 5, 8, 2, 7], size=10)
show(p)
II am using bokeh and would like to have logaritmic xaxis using Line of bokeh.charts.
But impiossible.
It is possible with basic glyphs and figure (bokeh.plotting) but not for Chart.
any idea?
Or did I miss something?
Here is the code :
import bokeh.models
import bokeh.plotting
import pandas as pd</br>
from bokeh.plotting import figure, show, output_file
from bokeh.layouts import column, row
from bokeh.charts import Line
plot=Line(df,x='x',y='y',x_axis_type='log')
output_file("cycling.html",title="cycling TOP")
layout=row(plot)
show(layout)
And here is the log:
AttributeError: unexpected attribute 'x_axis_type' to Chart, similar attributes are x_mapper_type
Thks.
David
Here there is an example using Line from bokeh.charts to create a line with the x axis in logarithmic scale:
import pandas as pd
from bokeh.plotting import show, output_file
from bokeh.layouts import row
from bokeh.charts import Line
import numpy as np
x = np.logspace(0,2,100)
d = {'x': x, 'y': 1/(20**2+x**2)**0.5}
df = pd.DataFrame(data=d)
plot=Line(df,x = 'x',y='y',x_mapper_type='log')
output_file("cycling.html",title="cycling TOP")
layout=row(plot)
show(layout)
Output: