bokeh patches stacked area chart with date - time

I am having trouble getting an stacked area chart with dates to populate. I have followed the example located in: Stack Overflow Example
However this example does not populate the data. Here is my code:
data = {'A': {0: 30.0, 1: 40.0, 2: 39.0, 3: 30.0, 4: 21.0},
'All': {0: 374.0, 1: 414.0, 2: 373.0, 3: 362.0, 4: 351.0},
'B': {0: 237.0, 1: 246.0, 2: 216.0, 3: 187.0, 4: 202.0},
'C': {0: 93.0, 1: 120.0, 2: 103.0, 3: 136.0, 4: 118.0},
'D': {0: 14.0, 1: 8.0, 2: 15.0, 3: 9.0, 4: 9.0},
'DEPT': {0: 'All', 1: 'All', 2: 'All', 3: 'All', 4: 'All'},
'E': {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 1.0},
'YEAR_WEEK': {0: '2017_01',
1: '2017_02',
2: '2017_03',
3: '2017_04',
4: '2017_05'}}
df_all = pd.DataFrame(data)
output_notebook()
def stacked(df):
df_top = df.cumsum(axis=1)
df_bottom = df_top.shift(axis=1).fillna({'A': 0})[::-1]
df_stack = pd.concat([df_bottom, df_top], ignore_index=True)
return df_stack
areas = stacked(df_all[['A','D','B','C','E']])
colors = brewer['Spectral'][areas.shape[1]]
x2 = np.hstack((df_all.index[::-1], df_all.index))
source = ColumnDataSource(df_all)
"""This works and shows data but does not have date tag"""
p = figure()
"""This does not show data but chart does have date tag"""
# p = figure(x_range = FactorRange(factors = df_all.YEAR_WEEK.tolist()), y_range =(0,1200))
p.patches([x2] * areas.shape[1], [areas[c].values for c in areas],color=colors, alpha=0.8, line_color=None)
p.xaxis.major_label_orientation = 'vertical'
show(p)

The current version of Bokeh is known to have this issue: https://github.com/bokeh/bokeh/issues/6458

Related

I need all calculated solutions that get close or equal to a static value, with predetermined values from an array of numbers

I need help with a problem and I'm struggling to figure out how to even start.
PROBLEM
I have a static value: 500000. Call it CAP.
I have a second, random-ish, value: 497548. Let's call it CURRENT. This value is usually between 1000 and 4000 below CAP.
I need to get CURRENT as close or equal to CAP with a combination of predetermined values, and I want to return every possible solution.
These values are as following:
const TURN_IN_VALUE = 398;
// The following is important for the returned solutions
// array index = rank. Index starts at 1.
const KILL_VALUES = {
60: [199, 210, 221, 233, 246, undefined, 274, 289, undefined, 321, 339, 358, 377],
59: [178, 188],
58: [159, undefined, 176],
57: [141, 1148],
56: [124, 131],
55: [109, 115, 121],
54: [95, 100],
53: [82],
52: [70],
51: [59],
50: [49],
49: [40, 42],
48: [32],
};
Values that are defined as undefined are unconfirmed and unsafe to use, so we skip them.
RULES
Solution should be no more than 5 off from CAP
Solution can not exceed CAP
KILL_VALUES can be used 2 times
TURN_IN_VALUE can be used 13 times
You can only add, never subtract
The returned solution should be something like
solutions = [
{
capAt: 499997,
kills: [{
60: 377,
rank: 13,
amount: 1,
}, {
53: 82,
rank: 1,
amount: 1,
}],
turnins: 5,
},
... // all other solutions
]

how to plot error bar only positive side in seaborn?

I´m trying to plot a chart and I have some problems to solve, sorry but I´m new in program language.
First one:
How to plot only one chart? I got that example from the internet and when a plot there is two figure for each code and two of them is blank.
The second one:
Is it possible to plot only a positive error bar?
Third one:
Is it possible to plot these two charts side by side in one figure?
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
Treat1 =pd.DataFrame({'Treatment': 1, 'weight': np.random.randint(low=1, high=100, size=40)})
Treat2 =pd.DataFrame({'Treatment': 2, 'weight': np.random.randint(low=1, high=100, size=40)})
df = pd.concat([Treat1, Treat2])
Treat3 =pd.DataFrame({'Treatment': 1, 'weight': np.random.randint(low=100, high=300, size=40)})
Treat4 =pd.DataFrame({'Treatment': 2, 'weight': np.random.randint(low=100, high=300, size=40)})
df2 = pd.concat([Treat3, Treat4])
sns.set(style="ticks")
fig, ax = plt.subplots()
color_map = dict(pos="indianred", neg="steelblue")
g = sns.catplot(x= "Treatment", y="weight", hue="Treatment", capsize=.07, ci ="sd",
data=df, kind="bar", palette = 'coolwarm', edgecolor="white")
plt.text(-0.22,99, "B")
plt.text(1.18,99, "A")
plt.ylabel('weight, kg')
plt.xticks([-0.2, 1.2], ['Group 1', 'Group 2'])
plt.ylim(0, 100)
color_map = dict(pos="indianred", neg="steelblue")
g = sns.catplot(x= "Treatment", y="weight", hue="Treatment", capsize=.07, ci ="sd",
data=df2, kind="bar", palette = 'coolwarm', edgecolor="white")
plt.text(-0.22,300, "B")
plt.text(1.18,300, "A")
plt.ylabel('weight, kg')
plt.xticks([-0.2, 1.2], ['Group 1', 'Group 2'])
plt.ylim(0, 300)
Thank you so much!
A seaborn catplot is a figure level plot, which creates and occupies a new figure. To have such a plot as a subplot, sns.barplot can be called directly. Supplying an ax tells into which subplot the barplot should go.
The barplot gets a legend, which in this case is superfluous, but it can be removed.
To only have the upper error bar visible, the rectangles of the bars can be plot on top of them. A zorder larger than the zorder of the lines of the errorbar (2) takes care of this.
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
Treat1 = pd.DataFrame({'Treatment': 1, 'weight': np.random.randint(low=1, high=100, size=40)})
Treat2 = pd.DataFrame({'Treatment': 2, 'weight': np.random.randint(low=1, high=100, size=40)})
df1 = pd.concat([Treat1, Treat2])
Treat3 = pd.DataFrame({'Treatment': 1, 'weight': np.random.randint(low=100, high=300, size=40)})
Treat4 = pd.DataFrame({'Treatment': 2, 'weight': np.random.randint(low=100, high=300, size=40)})
df2 = pd.concat([Treat3, Treat4])
sns.set(style="ticks")
fig, axs = plt.subplots(ncols=2, figsize=(10, 4))
for ax, df, height in zip(axs, [df1, df2], [100, 300]):
color_map = {1: "indianred", 2: "steelblue"}
g = sns.barplot(x="Treatment", y="weight", hue="Treatment", capsize=.07, ci="sd",
data=df, palette=color_map, edgecolor="white", ax=ax)
g.legend_.remove()
for bar in g.patches:
bar.set_zorder(3)
ax.text(-0.2, height * 0.95, "B", ha='center')
ax.text(1.2, height * 0.95, "A", ha='center')
ax.set_ylabel('weight, kg')
ax.set_xticks([-0.2, 1.2])
ax.set_xticklabels(['Group 1', 'Group 2'])
ax.set_ylim(0, height)
plt.tight_layout()
plt.show()
PS: Note that the code can be simplified somewhat if you don't use hue=. This also puts the bars in a more logical position.
fig, axs = plt.subplots(ncols=2, figsize=(10, 4))
for ax, df, height in zip(axs, [df1, df2], [100, 300]):
color_map = {1: "indianred", 2: "steelblue"}
g = sns.barplot(x="Treatment", y="weight", capsize=.07, ci="sd",
data=df, palette=color_map, edgecolor="white", ax=ax)
for bar in g.patches:
bar.set_zorder(3)
ax.text(0, height * 0.97, "B", ha='center', va='top')
ax.text(1, height * 0.97, "A", ha='center', va='top')
ax.set_ylabel('weight, kg')
ax.set_ylim(0, height)
ax.set_xticklabels(['Group 1', 'Group 2'])
plt.tight_layout()
plt.show()

scss bootstrap 4 overwrite map

I'm trying my hand at scss using Bootstrap 4 and I don't know how to overwrite variable (using map) correclty
custom.scss
// Your variable overrides
$primary: rgb(40, 167, 36);
$spacer: 1;
$spacers: (
0: 0,
1: ($spacer * .2),
2: ($spacer * 3),
3: $spacer,
4: ($spacer * 8),
5: ($spacer * 12),
6: ($spacer * 50)
);
// Bootstrap and its default variables
#import "../node_modules/bootstrap/scss/bootstrap";
Primary color overwrite works fine but the spacers don't.
As is it now it seems like all the value are equal to 0, whenever I add a class like "mt-5" it doesn't change anything.
I don't know what I'm doing wrong.
Here's how to add spacers to the map. The issue is that the spacer has no units. Use px or rem to define the spacer unit...
$spacer: 1rem;
$spacers: (
0: 0,
1: ($spacer * .2),
2: ($spacer * 3),
3: $spacer,
4: ($spacer * 8),
5: ($spacer * 12),
6: ($spacer * 50)
);
https://www.codeply.com/go/TY8XqnvzO9

Lua Missing } unexpected

function love.load()
Tileset = love.graphics.newImage('countryside.png')
TileW, TileH = 32, 32
local tilesetW, tilesetH = Tileset:getWidth(), Tileset:getHeight()
Quads = {
love.graphics.newQuad(0, 0, TileW, TileH, tilesetW, tilesetH) -- 1 = grass
love.graphics.newQuad(32, 0, TileW, TileH, tilesetW, tilesetH) -- 2 = box
love.graphics.newQuad(0, 32, TileW, TileH, tilesetW, tilesetH) -- 3 = flowers
love.graphics.newQuad(32, 32, TileW, TileH, tilesetW, tilesetH) -- 4 = box
}
TileTable = {
{1, 1, 1},
{1, 2, 1},
{1, 1, 1}
}
end
This code gives this error:
Syntax error: main.lua:9: '}' expected (to close '{' at line 7) near 'love'
I don't understand it. Anyone got any help?
In Lua, an array is initialized as below, hope it helps:
Quads = {
love.graphics.newQuad(0, 0, TileW, TileH, tilesetW, tilesetH), -- 1 = grass
love.graphics.newQuad(32, 0, TileW, TileH, tilesetW, tilesetH), -- 2 = box
love.graphics.newQuad(0, 32, TileW, TileH, tilesetW, tilesetH), -- 3 = flowers
love.graphics.newQuad(32, 32, TileW, TileH, tilesetW, tilesetH), -- 4 = box
}

Dynamic image cropping in Tensorflow

I'm trying to figure out how to take a crop of an image determined dynamically in Tensorflow. Below is an example of what I am trying to accomplish, however I can't seem to make it work. Essentially, I want to feed images and the crop values for that image within the graph, and then continue on with other computations on those cropped pieces. My current attempt:
import tensorflow as tf
from matplotlib import pyplot as plt
import numpy as np
sess = tf.InteractiveSession()
img1 = np.random.random([400, 600, 3])
img2 = np.random.random([400, 600, 3])
img3 = np.random.random([400, 600, 3])
images = [img1, img2, img3]
img1_crop = [100, 100, 100, 100]
img2_crop = [200, 150, 100, 100]
img3_crop = [150, 200, 100, 100]
crop_values = [img1_crop, img2_crop, img3_crop]
def crop_image(img, crop):
tf.image.crop_to_bounding_box(img,
crop[0],
crop[1],
crop[2],
crop[3])
image_placeholder = tf.placeholder("float", [None, 400, 600, 3])
crop_placeholder = tf.placeholder(dtype=tf.int32)
sess.run(tf.global_variables_initializer())
cropped_image = tf.map_fn(lambda img, crop: crop_image(img, crop), elems=[image_placeholder, crop_placeholder])
result = sess.run(cropped_image, feed_dict={image_placeholder: images, crop_placeholder:crop_values})
plt.imshow(result)
plt.show()
/Users/p111/anaconda/bin/python /Users/p111/PycharmProjects/analysis_code/testing.py
Traceback (most recent call last):
File "/Users/p111/PycharmProjects/analysis_code/testing.py", line 31, in
cropped_image = tf.map_fn(lambda img, crop: crop_image(img, crop), elems=[image_placeholder, crop_placeholder])
File "/Users/p111/anaconda/lib/python3.5/site-packages/tensorflow/python/ops/functional_ops.py", line 390, in map_fn
swap_memory=swap_memory)
File "/Users/p111/anaconda/lib/python3.5/site-packages/tensorflow/python/ops/control_flow_ops.py", line 2636, in while_loop
result = context.BuildLoop(cond, body, loop_vars, shape_invariants)
File "/Users/p111/anaconda/lib/python3.5/site-packages/tensorflow/python/ops/control_flow_ops.py", line 2469, in BuildLoop
pred, body, original_loop_vars, loop_vars, shape_invariants)
File "/Users/p111/anaconda/lib/python3.5/site-packages/tensorflow/python/ops/control_flow_ops.py", line 2419, in _BuildLoop
body_result = body(*packed_vars_for_body)
File "/Users/p111/anaconda/lib/python3.5/site-packages/tensorflow/python/ops/functional_ops.py", line 380, in compute
packed_fn_values = fn(packed_values)
TypeError: () missing 1 required positional argument: 'crop'
Edit: It appears that elems will only accept a single tensor. Which means I would need to somehow combine my two tensors into one, and then unpack it in my function to get the values out. I'm not sure how I would perform that kind of tensor manipulation. I have found the glimpse method already and that does work, however I am wondering if the same can be done with this specific method. Mostly, I'm wondering how you would combine and then split a pair of tensors so it can be used in this method.
I saw this code from here.
elems = (np.array([1, 2, 3]), np.array([-1, 1, -1]))
alternate = map_fn(lambda x: x[0] * x[1], elems, dtype=tf.int64)
# alternate == [-1, 2, -3]
It is possible to use a tuple or a list to pack several elements into one so I tried this.
import tensorflow as tf
from matplotlib import pyplot as plt
import numpy as np
sess = tf.InteractiveSession()
img1 = np.random.random([400, 600, 3])
img2 = np.random.random([400, 600, 3])
img3 = np.random.random([400, 600, 3])
images = np.array([img1, img2, img3])
# images = tf.convert_to_tensor(images) # it can be uncommented.
img1_crop = [100, 100, 100, 100]
img2_crop = [200, 150, 100, 100]
img3_crop = [150, 200, 100, 100]
crop_values = np.array([img1_crop, img2_crop, img3_crop])
# crop_values = tf.convert_to_tensor(crop_values) # it can be uncommented.
def crop_image(img, crop):
return tf.image.crop_to_bounding_box(img,
crop[0],
crop[1],
crop[2],
crop[3])
fn = lambda x: crop_image(x[0], x[1])
elems = (images, crop_values)
cropped_image = tf.map_fn(fn, elems=elems, dtype=tf.float64)
result = sess.run(cropped_image)
print result.shape
plt.imshow(result[0])
plt.show()
It works on my machine with tf version 0.11 and python2. Hope this can help you.
Couple of things :
You do not have a return statement in the crop_image function.
map_fn accepts a single argument.
I strongly advise you to separate the graph definition and the session usage.
--
# Graph def
def crop_image(img, crop):
return tf.image.crop_to_bounding_box(img,
crop[0],
crop[1],
crop[2],
crop[3])
image_placeholder = tf.placeholder(tf.float32, [None, 400, 600, 3])
crop_placeholder = tf.placeholder(dtype=tf.int32)
cropped_image = tf.map_fn(lambda inputs: crop_image(*inputs), elems=[image_placeholder, crop_placeholder], dtype=tf.float32)
# Session
sess = tf.InteractiveSession()
img1 = np.random.random([400, 600, 3])
img2 = np.random.random([400, 600, 3])
img3 = np.random.random([400, 600, 3])
images = [img1, img2, img3]
img1_crop = [100, 100, 100, 100]
img2_crop = [200, 150, 100, 100]
img3_crop = [150, 200, 100, 100]
crop_values = [img1_crop, img2_crop, img3_crop]
sess.run(tf.global_variables_initializer())
result = sess.run(cropped_image, feed_dict={image_placeholder: images, crop_placeholder:crop_values})
plt.imshow(result[0])
plt.show()
tf.map_fn(f, l) runs function f for every tensor in list l. In your case, your function expects 2 arguments, but since you supply a flat list, map_fn() sends them one by one. According to docs, map_fn() supports variable arity, so what you should do is something like this
tf.map_fn(lambda img, crop: crop_image(img, crop),
elems=([image_placeholder, crop_placeholder], ))
so the list you pass to map_fn contains pairs of arguments.

Resources