Altair chart not displaying when evaluated within a function - python-3.x

The following code, taken from the Altair docs, correctly displays in my Jupyter Lab notebook.
import altair as alt
from vega_datasets import data
source = data.seattle_temps.url
alt.Chart(
source,
title="2010 Daily High Temperature (F) in Seattle, WA"
).mark_rect().encode(
x='date(date):O',
y='month(date):O',
color=alt.Color('max(temp):Q', scale=alt.Scale(scheme="inferno")),
tooltip=[
alt.Tooltip('monthdate(date):T', title='Date'),
alt.Tooltip('max(temp):Q', title='Max Temp')
]
).properties(width=550)
However, if I cut and paste that exact code in a function, and then call the function, the chart no longer displays.
import altair as alt
from vega_datasets import data
def visualize():
source = data.seattle_temps.url
alt.Chart(
source,
title="2010 Daily High Temperature (F) in Seattle, WA"
).mark_rect().encode(
x='date(date):O',
y='month(date):O',
color=alt.Color('max(temp):Q', scale=alt.Scale(scheme="inferno")),
tooltip=[
alt.Tooltip('monthdate(date):T', title='Date'),
alt.Tooltip('max(temp):Q', title='Max Temp')
]
).properties(width=550)
visualize()
I read through Altair's display troubleshooting docs, and it seems the most common fix for this specific issue is to ensure that the chart is evaluated, which it is in this case. I'm not writing chart = alt.Chart(...), I'm skipping the assignment and going straight to the evaluation, which is why it worked outside of the function.
Why bother with the function? The reason I want to wrap it in a function is that I have a huge dataset (100 GBs) stored in a database. When I specify a filter to the database, the result is only 600 rows, so very manageable. I want to put this in a Jupyter Lab notebook and make the filter interative for non-technical users, so I created ipython widget for specifying the filter value. When a user specifies a filter in the widget, the widget needs a callback function to trigger the read from the database and produce the visual on the fly.

It is because your function is not returning anything. You are creating the chart, but not returning it so that the Jupyter Notebook can render it. If you write return alt.Chart(... it will work. If you don't want to return anything you can also append .display() to the chart spec inside the function (this also works for displaying charts in loops).

Related

Getting rid of print "<IPython.core.display.Markdown object>" when using `display`

I'm trying to create nice slides using jupyter notebook and RISE. One of my objectives is to display a pandas-dataframe in a Markdown cell in order to have some styling flexibility.
I am using the following code to display my dataframe in a Markdown cell:
{{Markdown(display(df_x))}}
After running this line, I get the following result:
image of dataframe displayed
I would like to get rid of the text printed below my dataframe (<IPython.core.display.Markdown object>).
I still haven't found a way to achieve this. Could someone give me a hand?
This is the library I'm working with:
from IPython.display import display
Not familiar with Markdown class so not sure why you need that but this text printed in the output cell is coming from the fact that this Markdown class is returning and object and since you're not assigning it to any variable the default behavior for the notebook is to run something like str(your_object) which correctly returns <IPython.core.display.Markdown object>.
So the easiest workaround would be to just assign it to some variable like this:
dummy_var = Markdown(display(df_x))
# or better yet:
_ = Markdown(display(df_x))

Display seaborn plots at some point later in code

Let's say at some point in my code, I have following two graphs: i.e. graph_p_changes and graph_p_contrib
line_grapgh_p_changes = df_p_change[['year','interest accrued', 'trade debts', 'other financial assets']].melt('year', var_name='variables', value_name='p_changes')
graph_p_changes = sns.factorplot(x="year", y="p_changes", hue='variables', data=line_grapgh_p_changes, height=5, aspect=2)
graph_p_changes.set(xlabel='year', ylabel='percentage change in self value across the years')
line_grapgh_p_contrib = df_p_contrib[['year','interest accrued', 'trade debts', 'other financial assets']].melt('year', var_name='variables', value_name='p_changes')
graph_p_contrib = sns.factorplot(x="year", y="p_changes", hue='variables', data=line_grapgh_p_contrib, height=5, aspect=2)
graph_p_contrib.set(xlabel='year', ylabel='percentage chnage in contribution to total value')
Now at some point later in my code, I just want to display one of the above two graphs. But when I do plt.show(), it displays both of the above graphs in my jupyter notebook. How can I display only one graph at any point in my code.
You'll want to refer to the assigned variable for each plot and then add .fig after that to redisplay it in a Jupyter notebook cell.
Specifically, in your case you'd reference graph_p_changes.fig or graph_p_contrib.fig in a cell and execute that cell to see an individual plot again.
This is similar to how you can show Seaborn's ClusterGrids again, see here. Because the title of your question said 'seaborn plots', I'll add for sake of completeness, this doesn't hold for plots like Seaborn's line plot (lineplot) or bar plot (barplot) , that produce AxesSubplot objects. There you use .figure, for example ax.figure to recall most of the examples listed on Seaborn's lineplot documentation.
Example catplots with code
This is using example code from here and seaborn's catplot documentation (see below) to make two plots. If this code was in one cell and then that cell was run, you'd see two plots in the output below it.
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
titanic = sns.load_dataset("titanic")
exercise = sns.load_dataset("exercise")
g = sns.catplot("alive", col="deck",
col_wrap=3, data=titanic[titanic.deck.notnull()],
kind="count", height=2.5, aspect=.8)
another_plot = sns.catplot(x="time", y="pulse", hue="kind", data=exercise)
Later, each can be displayed again individually as output of other cells with g.fig or another_plot.fig, depending on which plot you want to show.
Additionaly, I'll suggest to improve your long-term code viability, you may want to move on to using catplot in your plotting calls as that is what factorplot is now called in seaborn. See here where it says "factorplot still exists and will pass its arguments through to catplot() with a warning. It may be removed eventually, but the transition will be as gradual as possible."
UPDATE:
OP commented that what was desired was code allowing interspersed stdout/stderr output with plots at precise points among that stream and not just at the end.
For some reason, Seaborn plots (even simple line plots) don't seem to get 'captured' correctly with io.capture_output(), and so I had to use the %%capture cell magic command in the producing cell and combine the output in a separate cell. However, Plotly plots I tried based on example code are captured by io.capture_output() and allow facile intermixing all in the same cell. This is all illustrated in an example notebook available here; it is best viewed in static form here at nbviewer because nbviewer renders the Plotly plots while GitHub doesn't. The top of that notebook includes a link where you can launch an active Jupyter session where it will run.
Update related to this UPDATE:
In an insightful answer to 'seaborn stop figure from being visualized', ffrosch suggests you "can temporarily disable/enable the inline creation with plt.ioff() and plt.ion()." This may offer yet another way to fine-tune when Seabor plots show among the output and/or offer another way to constrain ouput since %%capture cell magic worked yet io.capture_output() did not. (I have yet to try this.)

gmplot Marker does not work after it marks 256 points

I am trying to mark a bunch of points on the map with gmplot and observed that after a certain point it stops marking and wipes out all the previously marked points. I debugged the gmplot.py module and saw that when the length of points array exceeds 256 this is happening without giving any error and warning.
self.points = [] on gmplot.py
Since I am very new to Python and OOPs concept, is there a way to override this and mark more than 256 points?
Are you using gmplot.GoogleMapPlotter.Scatter or gmplot.GoogleMapPlotter.Marker. I used either and was able to get 465 points for a project that I was working on. Is it possible it is an API key issue for you?
partial snippet of my code
import gmplot
import pandas as pd
# df is the database with Lat, Lon and formataddress columns
# change to list, not sure you need to do this. I think you can cycle through
# directly using iterrows. I have not tried that though
latcollection=df['Lat'].tolist()
loncollection=df['Lon'].tolist()
addcollection=df['formataddress'].tolist()
# center map with the first co-ordinates
gmaps2 = gmplot.GoogleMapPlotter(latcollection[0],loncollection[0],13,apikey='yourKey')
for i in range(len(latcollection)):
gmaps2.marker(latcollection[i],loncollection[i],color='#FF0000',c=None,title=str(i)+' '+ addcollection[i])
gmaps2.draw(newdir + r'\laplot_marker_full.html')
I could hover over the 465th point since I knew approximately where it was and I was able to get the title with str(464) <formataddress(464)>, since my array is indexed from 0
Make sure you check the GitHub site to modify your gmplot file, in case you are working with windows.

Python matplotlib pyplot module always draws on existing figure window when figure title is the same

I am a new python user but an experienced Matlab user. I am recently debugging a python script, and when I manually re-run the script multiple times, I found a somewhat annoying issue of matplotlib: it always draws on existing figure window, overlapping on existing plot, if the figure title is the same.
The script I am debugging looks like this:
import matplotlib.pyplot as plt
# Some calculations here
plt.figure('Results') # The script will only create one figure
# plot the data
# End of the script
A simple search on Google shows that if I don't explicitly specify figure title, or give each figure a different handle, matplotlib can create separate figure windows, and true, it works.
However, is there a way to create multiple figure windows with the same title, without giving them different handles (which in my case, I had to do it manually) in python? In Matlab it will always create separate figure window no matter what figure title you give it.
The argument to figure is an identifier. If it is left empty anew figure will be created, else the figure with that identifier will be activiated. The documentation makes this rather clear:
matplotlib.pyplot.figure(num=None, ...)
num : integer or string, optional, default: none
If not provided, a new figure will be created, and the figure number will be incremented. The figure objects holds this number in a number attribute. If num is provided, and a figure with this id already exists, make it active, and returns a reference to it. If this figure does not exists, create it and returns it. If num is a string, the window title will be set to this figure’s num.
Hence in order to create a new figure, leave this argument out or specify differing ones. In order to set the window's title, use set_window_title.
The following will create two figures with the same window title.
import matplotlib.pyplot as plt
plt.figure()
plt.gcf().canvas.set_window_title('Results')
plt.plot([1,2,3])
plt.figure()
plt.gcf().canvas.set_window_title('Results')
plt.plot([2,3,1], color="crimson")
plt.show()
From the first paragraph of your question, ...
when I manually re-run the script multiple times, I found a somewhat
annoying issue of matplotlib: it always draws on existing figure
window
I think that simply clearing the figure (at the start of the script) would make your repeated runs of the script useable.
import matplotlib.pyplot as plt
# compute results here - random here as a standin.
import numpy as np
x = np.random.randn(500)
plt.figure("Results"); plt.clf()
# plot results here...
plt.hist(x, bins=20, histtype='step')
Now, each time you run the script, you will draw the results on a blank canvas and not over the top of the old results.
The figures below illustrate the difference, after 3 runs of the script (in ipython): left - without the plt.clf(), and right - with plt.clf() at the start.

Using IronPython to set "Data Limit by Expression" on a visualization

How do I use IronPython to set the Data Limit By Expression field on a visualization?
(I mean an example of a simple IP script to set the Data Limit By Expression field on a visualization, I couldn't find one on the internet)
for any type of chart, if this is the only operation you need to do, you can use code like:
from Spotfire.Dxp.Application.Visuals import Visualization
viz = v.As[Visualization]()
print viz.Data.WhereClauseExpression # prints Python's nil value None
viz.Data.WhereClauseExpression = "[Column] = 'Value'"
print viz.Data.WhereClauseExpression # prints the above expression
in this example, v is a parameter pointing to the desired visualization. you could also look it up by name or ID or some other method.
if you're already manipulating this visualization with a script and just want to add a data limit, you can add this to your existing script without importing the Visualization class. every visualization type's Data object has this WhereClauseExpression property

Resources