Altair plots no longer displaying in VS Code - visual-studio-code

My Altair plots are no longer displaying in VS Code. Is anyone else having this issue? Matplotlib / pandas plots still show normally.
I used the simple bar chart example:
source = pd.DataFrame({
'a': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'],
'b': [28, 55, 43, 91, 81, 53, 19, 87, 52]
})
I can plot a pandas bar chart and get it to display:
source.plot.bar()
But I get no output when using Altair:
alt.Chart(source).mark_bar().encode(
x='a',
y='b'
)

I think that you need to call the chart, so first you need to save the chart as a variable and then call.
Chart1=alt.Chart(source).mark_bar().encode(
x='a',
y='b'
)
Chart1

Related

Consolidating multiple Python Charts into one Dashboard with Plotly-Dash

I have two different Python Dashboards, both of which visualize different types of financial data. I would like to have both figures on one single dashboard, one above the other. Would you happen to know if that is possible? If so, I'm sure one has to extend the entire app structure, including the layout and, more importantly, callback part. Has anyone any experience with merging two apps into one dashboard? Below you'll find my code I've assembled so far.
First Dashboard:
# import relevant packages
import pandas as pd
import numpy as np
import matplotlib as mpl
import plotly
import dash
import pyodbc
import plotly.express as px
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
data = [['2020-01-31', 100, 100, 100], ['2020-02-28', 101, 107, 99], ['2020-03-31', 104, 109, 93], ['2020-04-30', 112, 115, 94], ['2020-05-31', 112, 120, 89]]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['DATE', 'A', 'B', 'C'])
df = df.set_index('DATE')
df
# create the Dash app
app = dash.Dash()
# Set up the app layout
app.layout = html.Div(children=[
html.H1(children='Index Dashboard'),
html.P('''Pick one or more stocks from the dropdown below.'''),
dcc.Dropdown(id='index-dropdown',
options=[{'label': x, 'value': x}
for x in df.columns],
value='A',
multi=True, clearable=True),
dcc.Graph(id='price-graph')
])
# Set up the callback function
#app.callback(
Output(component_id='price-graph', component_property='figure'),
[Input(component_id='index-dropdown', component_property='value')],
)
def display_time_series(selected_index):
dff = df[selected_index] # Only columns selected in dropdown
fig = px.line(dff, x=df.index, y=selected_index, labels={'x': 'x axis label'})
fig.update_layout(
title="Price Index Development",
xaxis_title="Month",
yaxis_title="Price",
font=dict(size=13))
return fig
# Run local server
if __name__ == '__main__':
app.run_server(debug=True, use_reloader=False)
Second Dashboard:
data2 = [['A', 'B', 0.4], ['A', 'C', 0.5], ['A', 'D', 0.1], ['X', 'Y', 0.15], ['X', 'Z', 0.85]]
df2 = pd.DataFrame(data2, columns = ['BM_NAME', 'INDEX_NAME', 'WEIGHT'])
df2
barchart = px.bar(
data_frame=df2,
x=df2.BM_NAME,
y="WEIGHT",
color="INDEX_NAME",
opacity=0.9,
barmode='group')
barchart
# create the Dash app
app = dash.Dash()
# set up app layout
app.layout = html.Div(children=[
html.H1(children='BM Composition'),
dcc.Dropdown(id='BM-dropdown',
options=[{'label': x, 'value': x}
for x in df2.BM_NAME.unique()],
value='A',
multi=False, clearable=True),
dcc.Graph(id='bar-chart')
])
# set up the callback function
#app.callback(
Output(component_id="bar-chart", component_property="figure"),
[Input(component_id="BM-dropdown", component_property="value")],
)
def display_BM_composition(selected_BM):
filtered_BM = df2[df2.BM_NAME == selected_BM] # Only use unique values in column "BM_NAME" selected in dropdown
barchart = px.bar(
data_frame=filtered_BM,
x="BM_NAME",
y="WEIGHT",
color="INDEX_NAME",
opacity=0.9,
barmode='group')
return barchart
# Run local server
if __name__ == '__main__':
app.run_server(debug=True, use_reloader=False)
Many thanks in advance!

Rotated labels figure fit on Bokeh

A label gets fitted to figure (canvas) when placed by bokeh Label, but when it gets rotated that feature doesn't works.
from bokeh.models import ColumnDataSource, Label, LabelSet, Range1d
from bokeh.plotting import figure, output_file, show
output_file("label.html", title="label.py example")
source = ColumnDataSource(data=dict(height=[66, 71, 72, 68, 58, 62],
weight=[165, 189, 220, 141, 260, 174],
names=['Mark', 'Amir', 'Matt', 'Greg',
'Owen', 'Juan']))
p = figure(title='Dist. of 10th Grade Students at Lee High',
x_range=Range1d(140, 275))
p.scatter(x='weight', y='height', size=8, source=source)
p.xaxis[0].axis_label = 'Weight (lbs)'
p.yaxis[0].axis_label = 'Height (in)'
# Fitted data
citation1 = Label(x=260, y=58,
text='Fitted data even to figure', render_mode='css',
border_line_color='black', border_line_alpha=1.0,
background_fill_color='white', background_fill_alpha=1.0,
)
#Unfitted data
citation2 = Label(x=165, y=52,
text='Unfitted data, get out of canvas', render_mode='canvas',
border_line_color='black', border_line_alpha=1.0,
background_fill_color='white', background_fill_alpha=1.0,
angle = 90, angle_units='deg')
p.add_layout(citation1)
p.add_layout(citation2)
show(p)
Any idea how to make a rotated label that can always be shown in a figure?

Receiving key error on Networkx color_map

I'm having trouble getting the color_map to work with my networkx graph. It's fairly simply code but won't seem to work. I've looked through other similar threads but no the solutions don't seem to work.
I have data that look like this:
edgelist_manual = [{'source': 'ABE', 'target': 'ATL', 'value': 851},
{'source': 'ABE', 'target': 'BHM', 'value': 1},
{'source': 'ABE', 'target': 'CLE', 'value': 805}]
edgelist = pd.DataFrame(edgelist_manual)
nodelist_manual = [{'source': 'ABE', 'value': '4807', 'group': 0},
{'source': 'ABI', 'value': '2660', 'group': 4},
{'source': 'ABQ', 'value': '41146', 'group': 2}]
nodelist = pd.DataFrame(nodelist_manual)
I run the code below, but my color_map keep screwing up. I just get a key error on the 'group' reference.
import itertools
import copy
import networkx as nx
import pandas as pd
import matplotlib.pyplot as plt
nodelist = pd.read_csv('final_nodes.csv')
edgelist = pd.read_csv('final_edges.csv')
g = nx.Graph()
for i, elrow in edgelist.iterrows():
g.add_edge(elrow[0], elrow[1], attr_dict=elrow[2:].to_dict())
for i, nlrow in nodelist.iterrows():
g.node[nlrow['source']].update(nlrow[1:].to_dict())
color_map = {0: 'r', 1:'b', 2:'r', 3:'b', 4:'r', 5:'b'}
colors = [color_map[g.node[node]['group']] for node in g]
nx.draw(g, node_color=colors)
ax = plt.gca()
ax.collections[0].set_edgecolor("#555555")
plt.show()
The only difference from this and my code is that rather than creating the data manually I'm loading it from .csv. I've checked for trailing whitespaces on the feature labels but nothing. I don't understand indices well so I wonder if those are messing it up. Any ideas?
Thanks!

Some questions as for vue-chartjs

In Laravel 5.6 / vuejs 2.5 application I use vue-chartjs, but my charts looks like :
https://imgur.com/a/ru1dXlm
I want some more:
having several items(artists in my case) I want to see them half-transparent, just as in first example here http://demo.vue-chartjs.org/
having points with values shown as in first example at link above
I need to see all labels in x-direction( I fill labels parameter ) for here
If there source code of demo examples of link above > I searched and did not find...
Thanks!
Well, you should find everything you need in the documentation of chart.js and vue-chart.js
http://www.chartjs.org/docs/latest/
http://vue-chartjs.org/#/home?id=resources
You can add rgb values as a background color to make them transparent.
You can also use gradients as its just a canvas element.
Here is a tutorial:
https://hackernoon.com/creating-stunning-charts-with-vue-js-and-chart-js-28af584adc0a?source=user_profile---------5----------------
Here is the source code of the vue-chartjs demo page:
https://github.com/apertureless/vue-chartjs-demo
(It's a bit outdated as with v3 the creation of chart components changed a bit)
It seems you did not filled the labels correctly.
{
labels: ['Here', 'are', 'your', 'x-axis', 'labels'],
datasets: [
{
label: 'artist 1',
backgroundColor: 'rgba(75, 192, 192, 0.2)',
data: [0, 1, 2, 3, 4],
},
{
label: 'artist 2',
backgroundColor: 'rgba(255, 99, 132, 0.2)',
data: [0, 1, 2, 3, 4],
},
],
}

Use of regex on iso-2022-jp encoding with Python

I have some ISO-2022-JP encoded text.
Ex. :
まだ 正式 に 決まっ た わけ で は ない の で 。
According to the re library documentation, it can accept both ascii and unicode, so I tried to convert my text to unicode and to cut at the word level:
text.decode('iso-2022-jp')
print(text)
print(re.findall(r"[\w']+", text))
However, here is the kind of output I get:
まだ 正式 に 決まっ た わけ で は ない の で 。
['B', 'B', 'B', 'B', 'B', '5', '0', 'B', 'B', 'K', 'B', 'B7h', 'C', 'B', 'B', 'B', 'B', 'o', '1', 'B', 'B', 'G', 'B', 'B', 'O', 'B', 'B', 'J', 'B', 'B', 'N', 'B', 'B', 'G', 'B', 'B', 'B']
What do I do wrong ?
Thanks!
Your code work for me. (Python 3.3.0)
>>> text = "まだ 正式 に 決まっ た わけ で は ない の で 。"
>>> print(text)
まだ 正式 に 決まっ た わけ で は ない の で 。
>>> import re
>>> re.findall(r"[\w']+", text)
['まだ', '正式', 'に', '決まっ', 'た', 'わけ', 'で', 'は', 'ない', 'の', 'で']
BTW, you didn't assign the decoded string to text.
text = text.decode('iso-2022-jp')
UPDATE
I get following result, if I decode text as ascii (discarding non-ascii character).
>>> re.findall(r"[\w']+", text.encode('iso-2022-jp').decode('ascii', 'ignore'))
['B', 'B', 'B', '5', '0', 'B', 'B', 'K', 'B', 'B7h', 'C', 'B', 'B', 'B', 'B', 'o', '1', 'B', 'B', 'G', 'B', 'B', 'O', 'B', 'B', 'J', 'B', 'B', 'N', 'B', 'B', 'G', 'B', 'B', 'B']
Seems like you're decode/encode incorrectly.
UPDATE2
If you read text from file, you don't need decode individual lines. Specify encoding in open() call.
import re
with open('results', 'r', encoding='iso-2022-jp') as f:
for line in f:
matches = re.findall(r"[\w']+", line)
if matches:
print(matches)