I have series, data and categories that I feed into a function to create a dodged bar using matplotlib.
I have managed to created a stacked chart, however I want to create a dodged bar.
This is what I have managed to create (stacked bar):
This is what I want to create (dodged bar):
#
# File: bar_dodged.py
# Version 1
# License: https://opensource.org/licenses/GPL-3.0 GNU Public License
#
import matplotlib.pyplot as plt
import numpy as np
def bar_dodged(series_labels: list = ['Minor', 'Low'],
data: list = [
[1, 2, 3, 4],
[5, 6, 7, 8]
],
category_labels: list = ['01/2023', '02/2023', '03/2023', '04/2023'],
bar_background_colors: list = ['tab:orange', 'tab:green'],
bar_text_colors: list = ['white', 'grey'],
direction: str = "vertical",
x_labels_rotation: int = 0,
y_label: str = "Quantity (units)",
figsize: tuple = (18, 5),
reverse: bool = False,
file_path: str = ".",
file_name: str = "bar_dodged.png"):
"""
:param series_labels:
:param data:
:param category_labels:
:param bar_background_colors:
:param bar_text_colors:
:param direction:
:param x_labels_rotation:
:param y_label:
:param figsize:
:param reverse:
:param file_path:
:param file_name:
:return:
"""
# Debugging
print(f"\n")
print(f"bar_dodged() :: series_labels={series_labels}")
print(f"bar_dodged() :: data={data}")
print(f"bar_dodged() :: category_labels={category_labels}")
print(f"bar_dodged() :: bar_background_colors={bar_background_colors}")
# Set size
plt.figure(figsize=figsize)
# Plot!
show_values = True
value_format = "{:.0f}"
grid = False
ny = len(data[0])
ind = list(range(ny))
axes = []
cum_size = np.zeros(ny)
data = np.array(data)
if reverse:
data = np.flip(data, axis=1)
category_labels = reversed(category_labels)
for i, row_data in enumerate(data):
color = bar_background_colors[i] if bar_background_colors is not None else None
axes.append(plt.bar(ind, row_data, bottom=cum_size,
label=series_labels[i], color=color))
cum_size += row_data
if category_labels:
plt.xticks(ind, category_labels)
if y_label:
plt.ylabel(y_label)
plt.legend()
if grid:
plt.grid()
if show_values:
for axis in axes:
for bar in axis:
w, h = bar.get_width(), bar.get_height()
plt.text(bar.get_x() + w/2, bar.get_y() + h/2,
value_format.format(h), ha="center",
va="center")
# Rotate
plt.xticks(rotation=x_labels_rotation)
# Two lines to make our compiler able to draw:
plt.savefig(f"{file_path}/{file_name}", bbox_inches='tight', dpi=200)
if __name__ == '__main__':
# Usage example:
series_labels = ['Globally', 'Customer']
data = [[9, 6, 5, 4, 8], [8, 5, 4, 3, 7]]
category_labels = ['Feb/2023', 'Dec/2022', 'Nov/2022', 'Oct/2022', 'Sep/2022']
bar_background_colors = ['#800080', '#ffa503']
bar_dodged(series_labels=series_labels, data=data, category_labels=category_labels,
bar_background_colors=bar_background_colors)
What do I have to change in my code in order to make the chart dodged?
To do that, you need to change just one line inside the for loop where you are drawing the bars. Change the axes.append() to below...
axes.append(plt.bar([element + 0.2*i for element in ind],
row_data, width = 0.2, #bottom=cum_size,
label=series_labels[i], color=color))
This will basically change the x position of the bar to 0,1,2.. (for the first run when 1=0) and add 0.2 for the second run. That that I have kept the bar width as 0.2 using width = 0.2. YOu can change it if you want thicker bars. Also, I have removed the bottom, which means, each bar/rectangle will be starting at 0. Hope this is what you are looking for...
Plot
Related
I have a dataset that is a list of lists.
Each list is a category to be plotted as a box plot.
Each list has a list of up to 9 components to be plotted into subplots.
The functions I am using is below was based on this answer. I pulled it out of my work and added some mock data. Should be a minimal example below.
neonDict = {
0:0, 1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8
}
import matplotlib as mpl
import matplotlib.pyplot as plt
def coloredBoxPlot(axis, data,edgeColor,fillColor):
bp = axis.boxplot(data,vert=False,patch_artist=True)
for element in ['boxes', 'whiskers', 'fliers', 'means', 'medians', 'caps']:
plt.setp(bp[element], color=edgeColor)
for patch in bp['boxes']:
patch.set(facecolor=fillColor)
return bp
def plotCalStats(data, prefix='Channel', savedir=None,colors=['#00597c','#a8005c','#00aeea','#007d50','#400080','#e07800'] ):
csize = mpl.rcParams['figure.figsize']
cdpi = mpl.rcParams['figure.dpi']
mpl.rcParams['figure.figsize'] = (12,8)
mpl.rcParams['figure.dpi'] = 1080
pkdata = []
labels = []
lstyles = []
fg, ax = plt.subplots(3,3)
for pk in range(len(neonDict)):
px = pk // 3
py = pk % 3
ax[px,py].set_xlabel('Max Pixel')
ax[px,py].set_ylabel('')
ax[px,py].set_title(str(neonDict[pk]) + ' nm')
pkdata.append([])
for cat in range(len(data)):
bp = ''
for acal in data[cat]:
for apeak in acal.peaks:
pkdata[apeak].append(acal.peaks[apeak][0])
for pk in range(9):
px = pk // 3
py = pk % 3
bp = coloredBoxPlot(ax[px,py], pkdata[pk], colors[cat], '#ffffff')
if len(data[cat]) > 0:
#print(colors[cat])
#print(bp['boxes'][0].get_edgecolor())
labels.append(prefix+' '+str(cat))
lstyles.append(bp['boxes'][0])
fg.legend(lstyles,labels)
fg.suptitle('Calibration Summary by '+prefix)
fg.tight_layout()
if savedir is not None:
plt.savefig(savedir + 'Boxplots.png')
plt.show()
mpl.rcParams['figure.figsize'] = csize
mpl.rcParams['figure.dpi'] = cdpi
return
class acal:
def __init__(self):
self.peaks = {}
for x in range(9):
self.peaks[x] = (np.random.randint(20*x,20*(x+1)),)
mockData = [[acal() for y in range(100)] for x in range(6)]
#Some unused channels
mockData[2] = []
mockData[3] = []
mockData[4] = []
plotCalStats(mockData)
So the issue is that the plot colors do not match the legend. Even if I restrict the data to only add a label if data exists (ensuring thus there is no issue with calling boxplots with an empty data set and not getting an appropriate PathPatch.
The printouts verify the colors are correctly stored in the PathPatch. (I can add my digits -> hex converter) if that is questioned.
Attached is the output. One can see I get a purple box but no purple in the legend. Purple is the 4th category which is empty.
Any ideas why the labels don't match the actual style? Thanks much!
EDITS:
To address question on 'confusing'.
I have six categories of data, each category is coming from a single event. Each event has 9 components. I want to compare all events, for each individual component, for each category on a single plot as shown below.
Each subplot is a individual component comprised from the series of data for each categorical (Channel).
So the link I have provided, (like I said, is adapted from) shows how to create a single box plot on one axis for 2 data sets. I've basically done the same thing for 6 data sets on 9 axis, where 3 data sets are empty (but don't have to be, I did it to illustrate the issue. If I have all 6 data sets there, how can you tell the colors are messed up?????)
Regarding the alpha:
The alphas are always 'ff' when giving only RGB data to matplotlib. If I call get_edgecolors, it will return a tuple (RGBA) where A = 1.0.
See commented out print statement.
EDIT2:
If I restrict it down to a single category, it makes the box plot view less confusing.
Single Example (see how box plot color is orange, figure says it's blue)
All colors off
Feel like this used to work....
Uncertain how the error presented as it did, but the issue has to do with reformatting the data before creating the box plot.
By removing pkdata.append([]) during the creation of the subplots before looping the categories and adding:
pkdata = [[],[],[],[],[],[],[],[],[]] during each iteration of the category loop fixed the issue. The former was sending in all previous channel data...
Output is now better. Full sol attached.
Likely, since the plot uses data from pkdata, the empty channel (data[cat]) plotted previous data (from data[cat-1]) as that was still in pkdata (actually, all previous data[cat] was still in pkdata) which was then plotted. I only check data[cat] for data on each loop to add to the legend. The legend was set up for channels 0,1,5, for example.. but we saw data for channel: 0 as 0, 0+1 as 1, 0+1 as 2, 0+1 as 3, 0+1 as 4, 0+1+5 as 5... thus channel 4 (purple) had data to plot but wasn't added to the legend. Giving the impression of 'misaligned' legends but rather unlegend data...
The single channel data is actually all 6 channels overlapping, the final channel 5 color being orange, overlapping all previous, namely the original channel 0 data to whom the data belongs and was properly added to the legend.
neonDict = {
0:0, 1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8
}
import matplotlib as mpl
import matplotlib.pyplot as plt
def getHex(r,g,b,a=1.0):
colors = [int(r * 255 ),int(g * 255 ),int(b * 255 ),int(a * 255) ]
s = '#'
for x in range(4):
cs = hex(colors[x])
if len(cs) == 3:
cs = cs + '0'
s += cs.replace('0x','')
return s
def getRGB(colstr):
try:
a = ''
r = int(colstr[1:3],16) / 255
g = int(colstr[3:5],16) / 255
b = int(colstr[5:7],16) / 255
if len (colstr) == 7:
a = 1.0
else:
a = int(colstr[7:],16) / 255
return (r,g,b,a)
except Exception as e:
print(e)
raise e
return
def compareHexColors(col1,col2):
try:
## ASSUME #RBG or #RBGA
## If less than 7, append the ff for the colors
if len(col1) < 9:
col1 += 'ff'
if len(col2) < 9:
col2 += 'ff'
return col1.lower() == col2.lower()
except Exception as e:
raise e
return False
def coloredBoxPlot(axis, data,edgeColor,fillColor):
bp = axis.boxplot(data,vert=False,patch_artist=True)
for element in ['boxes', 'whiskers', 'fliers', 'means', 'medians', 'caps']:
plt.setp(bp[element], color=edgeColor)
for patch in bp['boxes']:
patch.set(facecolor=fillColor)
return bp
def plotCalStats(data, prefix='Channel', savedir=None,colors=['#00597c','#a8005c','#00aeea','#007d50','#400080','#e07800'] ):
csize = mpl.rcParams['figure.figsize']
cdpi = mpl.rcParams['figure.dpi']
mpl.rcParams['figure.figsize'] = (12,8)
mpl.rcParams['figure.dpi'] = 1080
pkdata = []
labels = []
lstyles = []
fg, ax = plt.subplots(3,3)
for pk in range(len(neonDict)):
px = pk // 3
py = pk % 3
ax[px,py].set_xlabel('Max Pixel')
ax[px,py].set_ylabel('')
ax[px,py].set_title(str(neonDict[pk]) + ' nm')
for cat in range(len(data)):
bp = ''
pkdata = [[],[],[],[],[],[],[],[],[]]
for acal in data[cat]:
for apeak in acal.peaks:
pkdata[apeak].append(acal.peaks[apeak][0])
for pk in range(9):
px = pk // 3
py = pk % 3
bp = coloredBoxPlot(ax[px,py], pkdata[pk], colors[cat], '#ffffff')
if len(data[cat]) > 0:
print(compareHexColors(colors[cat],getHex(*bp['boxes'][0].get_edgecolor())))
labels.append(prefix+' '+str(cat))
lstyles.append(bp['boxes'][0])
fg.legend(lstyles,labels)
fg.suptitle('Calibration Summary by '+prefix)
fg.tight_layout()
if savedir is not None:
plt.savefig(savedir + 'Boxplots.png')
plt.show()
mpl.rcParams['figure.figsize'] = csize
mpl.rcParams['figure.dpi'] = cdpi
return
class acal:
def __init__(self,center):
self.peaks = {}
for x in range(9):
self.peaks[x] = [10*x + (center) + (np.random.randint(10)-1)/2.0,0,0]
mockData = [[acal(x) for y in range(1000)] for x in range(6)]
#Some unused channels
mockData[2] = []
mockData[3] = []
mockData[4] = []
plotCalStats(mockData)
I am working on a human pose prediction project, and I need to plot a human 3D pose skeleton from a numerical dataset, to compare ground truth and predicted values. like this image: enter image description here
Already I am using this simple code,
ax = plt.axes(projection='3d')
fig = plt.figure()
fig = plt.figure()
xdata = np.array(data[values])
ydata = np.array(data[values])
zdata = np.array(data[values])
ax.scatter3D(xdata, ydata, zdata, c=zdata)
plt.show()
but it shows me the points in a 3D plot, I know it isn't correct, So here is the question :
**Is there any library or function to call? (Since already I use scatter, and I know it is wrong)
[my dataset has 6395 rows and 54columns, And I am searching for a method to show for example 10 different poses every time or less.]
import typing as tp
import numpy as np
import matplotlib.pyplot as plt
def get_chain_dots(
dots: np.ndarray, # shape == (n_dots, 3)
chain_dots_indexes: tp.List[int], # length == n_dots_in_chain
# in continuous order, i.e.
# left_hand_ix >>> chest_ix >>> right_hand_ix
) -> np.ndarray: # chain of dots
"""Get continuous chain of dots
chain_dots_indexes -
indexes of points forming a continuous chain;
example of chain: [hand_l, elbow_l, shoulder_l, chest, shoulder_r, elbow_r, hand_r]
"""
return dots[chain_dots_indexes]
def get_chains(
dots: np.ndarray, # shape == (n_dots, 3)
spine_chain_ixs: tp.List[int], # pelvis >>> chest >>> head
hands_chain_ixs: tp.List[int], # left_hand >>> chest >>> right_hand
legs_chain_ixs: tp.List[int] # left_leg >>> pelvis >>> right_leg
):
return (get_chain_dots(dots, spine_chain_ixs),
get_chain_dots(dots, hands_chain_ixs),
get_chain_dots(dots, legs_chain_ixs))
def subplot_nodes(dots: np.ndarray, # shape == (n_dots, 3)
ax):
return ax.scatter3D(*dots.T, c=dots[:, -1])
def subplot_bones(chains: tp.Tuple[np.ndarray, ...], ax):
return [ax.plot(*chain.T) for chain in chains]
def plot_skeletons(
skeletons: tp.Sequence[np.ndarray],
chains_ixs: tp.Tuple[tp.List[int], tp.List[int], tp.List[int]]):
fig = plt.figure()
for i, dots in enumerate(skeletons, start=1):
chains = get_chains(dots, *chains_ixs)
ax = fig.add_subplot(2, 5, i, projection='3d')
subplot_nodes(dots, ax)
subplot_bones(chains, ax)
plt.show()
def test():
"""Plot random poses of simplest skeleton"""
skeletons = np.random.standard_normal(size=(10, 11, 3))
chains_ixs = ([0, 1, 2, 3, 4], # hand_l, elbow_l, chest, elbow_r, hand_r
[5, 2, 6], # pelvis, chest, head
[7, 8, 5, 9, 10]) # foot_l, knee_l, pelvis, knee_r, foot_r
plot_skeletons(skeletons, chains_ixs)
if __name__ == '__main__':
test()
To plot gradient color lines see.
And additionally docs.
I have a data frame like the below:
Every row represents a person. They stay at 3 different locations for some time given on the dataframe. The first few people don't stay at location1 but they "born" at location2. The rest of them stay at every locations (3 locations).
I would like to animate every person at the given X, Y coordinates given on the data frame and represent them as dots or any other shape. Here is the flow:
Every person should appear at the first given location (location1) at the given time. Their color should be blue at this state.
Stay at location1 until location2_time and then appear at location2. Their color should be red at this state.
Stay at location2 until location3_time and then appear at location3. Their color should be red at this state.
Stay at location3 for 3 seconds and disappear forever.
There can be several people on the visual at the same time. How can I do that?
There are some good answers on the below links. However, on these solutions, points don't disappear.
How can i make points of a python plot appear over time?
How to animate a scatter plot?
The following is an implementation with python-ffmpeg, pandas, matplotlib, and seaborn. You can find output video on my YouTube channel (link is unlisted).
Each frame with figures is saved directly to memory. New figures are generated only when the state of the population changes (person appears/moves/disappears).
You should definetely separate this code into smaller chunks if you are using this in a Python package:
from numpy.random import RandomState, SeedSequence
from numpy.random import MT19937
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
import ffmpeg
RESOLUTION = (12.8, 7.2) # * 100 pixels
NUMBER_OF_FRAMES = 900
class VideoWriter:
# Courtesy of https://github.com/kylemcdonald/python-utils/blob/master/ffmpeg.py
def __init__(
self,
filename,
video_codec="libx265",
fps=15,
in_pix_fmt="rgb24",
out_pix_fmt="yuv420p",
input_args=None,
output_args=None,
):
self.filename = filename
self.process = None
self.input_args = {} if input_args is None else input_args
self.output_args = {} if output_args is None else output_args
self.input_args["r"] = self.input_args["framerate"] = fps
self.input_args["pix_fmt"] = in_pix_fmt
self.output_args["pix_fmt"] = out_pix_fmt
self.output_args["vcodec"] = video_codec
def add(self, frame):
if self.process is None:
height, width = frame.shape[:2]
self.process = (
ffmpeg.input(
"pipe:",
format="rawvideo",
s="{}x{}".format(width, height),
**self.input_args,
)
.filter("crop", "iw-mod(iw,2)", "ih-mod(ih,2)")
.output(self.filename, **self.output_args)
.global_args("-loglevel", "quiet")
.overwrite_output()
.run_async(pipe_stdin=True)
)
conv = frame.astype(np.uint8).tobytes()
self.process.stdin.write(conv)
def close(self):
if self.process is None:
return
self.process.stdin.close()
self.process.wait()
def figure_to_array(figure):
"""adapted from: https://stackoverflow.com/questions/21939658/"""
figure.canvas.draw()
buf = figure.canvas.tostring_rgb()
n_cols, n_rows = figure.canvas.get_width_height()
return np.frombuffer(buf, dtype=np.uint8).reshape(n_rows, n_cols, 3)
# Generate data for the figure
rs1 = RandomState(MT19937(SeedSequence(123456789)))
time_1 = np.round(rs1.rand(232) * NUMBER_OF_FRAMES).astype(np.int16)
time_2 = time_1 + np.round(rs1.rand(232) * (NUMBER_OF_FRAMES - time_1)).astype(np.int16)
time_3 = time_2 + np.round(rs1.rand(232) * (NUMBER_OF_FRAMES - time_2)).astype(np.int16)
loc_1_x, loc_1_y, loc_2_x, loc_2_y, loc_3_x, loc_3_y = np.round(rs1.rand(6, 232) * 100, 1)
df = pd.DataFrame({
"loc_1_time": time_1,
"loc_1_x": loc_1_x,
"loc_1_y": loc_1_y,
"loc_2_time": time_2,
"loc_2_x": loc_2_x,
"loc_2_y": loc_2_y,
"loc_3_time": time_3,
"loc_3_x": loc_3_x,
"loc_3_y": loc_3_y,
})
"""The stack answer starts here"""
# Add extra column for disappear time
df["disappear_time"] = df["loc_3_time"] + 3
all_times = df[["loc_1_time", "loc_2_time", "loc_3_time", "disappear_time"]]
change_times = np.unique(all_times)
# Prepare ticks for plotting the figure across frames
x_values = df[["loc_1_x", "loc_2_x", "loc_3_x"]].values.flatten()
x_ticks = np.array(np.linspace(x_values.min(), x_values.max(), 6), dtype=np.uint8)
y_values = df[["loc_1_y", "loc_2_y", "loc_3_y"]].values.flatten()
y_ticks = np.array(np.round(np.linspace(y_values.min(), y_values.max(), 6)), dtype=np.uint8)
sns.set_theme(style="whitegrid")
video_writer = VideoWriter("endermen.mp4")
if 0 not in change_times:
# Generate empty figure if no person arrive at t=0
fig, ax = plt.subplots(figsize=RESOLUTION)
ax.set_xticklabels(x_ticks)
ax.set_yticklabels(y_ticks)
ax.set_title("People movement. T=0")
video_writer.add(figure_to_array(fig))
loop_range = range(1, NUMBER_OF_FRAMES)
else:
loop_range = range(NUMBER_OF_FRAMES)
palette = sns.color_palette("tab10") # Returns three colors from the palette (we have three groups)
animation_data_df = pd.DataFrame(columns=["x", "y", "location", "index"])
for frame_idx in loop_range:
if frame_idx in change_times:
plt.close("all")
# Get person who appears/moves/disappears
indexes, loc_nums = np.where(all_times == frame_idx)
loc_nums += 1
for i, loc in zip(indexes, loc_nums):
if loc != 4:
x, y = df[[f"loc_{loc}_x", f"loc_{loc}_y"]].iloc[i]
if loc == 1: # location_1
animation_data_df = animation_data_df.append(
{"x": x, "y": y, "location": loc, "index": i},
ignore_index=True
)
else:
data_index = np.where(animation_data_df["index"] == i)[0][0]
if loc in (2, 3): # location_2 or 3
animation_data_df.loc[[data_index], :] = x, y, loc, i
elif loc == 4: # Disappear
animation_data_df.iloc[data_index] = np.nan
current_palette_size = np.sum(~np.isnan(np.unique(animation_data_df["location"])))
fig, ax = plt.subplots(figsize=RESOLUTION)
sns.scatterplot(
x="x", y="y", hue="location", data=animation_data_df, ax=ax, palette=palette[:current_palette_size]
)
ax.set_xticks(x_ticks)
ax.set_xticklabels(x_ticks)
ax.set_yticks(y_ticks)
ax.set_yticklabels(y_ticks)
ax.legend(loc="center left", bbox_to_anchor=(1, 0.5))
ax.set_title(f"People movement. T={frame_idx}")
video_writer.add(figure_to_array(fig))
video_writer.close()
Edit: There was a bug in which location_3 wasn't removed after 3 seconds. Fixed now.
Modifying the code from this question to only include the positions you want automatically removes the old ones if the old position isn't included in the new ones. This doesn't change if you want to animate by time or iterations or anything else. I have opted to use iterations here since it's easier and I don't know how you are handling your dataset. The code does have one bug though, the last point (or points if they last the same amount of time) remaining won't disappear, this can be solved easily if you don't want to draw anything again, if you do though for exaple in case you there is a gap in the data with no people and then the data resumes I haven't found any workarounds
import math
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
#The t0,t1,t2,t3 are the times (in iterations) that the position changes
#If t0 is None then the person will never be displayed
people = [
# t0 x1 y1 t1 x2 y2 t2 x3 y3 t4
[ 0, 1, 0.1, 1, 2, 0.2, 2, 3, 0.3, 3],
[ 2, None, None, None, 2, 1, 3, 4, 1, 7],
[ 2, float("NaN"), float("NaN"), float("NaN"), 2, 0.8, 4, 4, 0.8, 10],
]
fig = plt.figure()
plt.xlim(0, 5)
plt.ylim(0, 1)
graph = plt.scatter([], [])
def animate(i):
points = []
colors = []
for person in people:
if person[0] is None or math.isnan(person[0]) or i < person[0]:
continue
# Position 1
elif person[3] is not None and not (math.isnan(person[3])) and i <= person[3]:
new_point = [person[1], person[2]]
color = "b"
# Position 2
elif person[6] is not None and not (math.isnan(person[6])) and i <= person[6]:
new_point = [person[4], person[5]]
color = "r"
# Position 3
elif person[9] is not None and not (math.isnan(person[9])) and i <= person[9]:
new_point = [person[7], person[8]]
color = "r"
else:
people.remove(person)
new_point = []
if new_point != []:
points.append(new_point)
colors.append(color)
if points != []:
graph.set_offsets(points)
graph.set_facecolors(colors)
else:
# You can use graph.remove() to fix the last point not disappiring but you won't be able to plot anything after that
# graph.remove()
pass
return graph
ani = FuncAnimation(fig, animate, repeat=False, interval=500)
plt.show()
I'm making a plot to compare band structure calculations from two different methods. This means plotting multiple lines for each set of data. I want to have a set of widgets that controls each set of data separately. The code below works if I only plot one set of data, but I can't get the widgets to work properly for two sets of data.
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, TextBox
#cols = ['blue', 'red', 'green', 'purple']
cols = ['#3f54bf','#c14142','#59bf3f','#b83fbf']
finam = ['wan_band.dat','wan_band.pwx.dat']
#finam = ['wan_band.dat'] # this works
lbot = len(finam)*0.09 + 0.06
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=lbot)
ax.margins(x=0) # lines go to the edge of the horizontal axes
def setlines(lines, txbx1, txbx2):
''' turn lines on/off based on text box values '''
try:
mn = int(txbx1) - 1
mx = int(txbx2) - 1
for ib in range(len(lines)):
if (ib<mn) or (ib>mx):
lines[ib].set_visible(False)
else :
lines[ib].set_visible(True)
plt.draw()
except ValueError as err:
print('Invalid range')
#end def setlines(cnt, lines, txbx1, txbx2):
def alphalines(lines, valin):
''' set lines' opacity '''
maxval = int('ff',16)
maxval = hex(int(valin*maxval))[2:]
for ib in range(bcnt):
lines[ib].set_color(cols[cnt]+maxval)
plt.draw()
#end def alphalines(lines, valtxt):
lines = [0]*len(finam) # 2d list to hold Line2Ds
txbox1 = [0]*len(finam) # list of Lo Band TextBoxes
txbox2 = [0]*len(finam) # lsit of Hi Band TextBoxes
alslid = [0]*len(finam) # list of Line Opacity Sliders
for cnt, fnam in enumerate(finam):
ptcnt = 0 # point count
fid = open(fnam, 'r')
fiit = iter(fid)
for line in fiit:
if line.strip() == '' :
break
ptcnt += 1
fid.close()
bandat_raw = np.loadtxt(fnam)
bcnt = int(np.round((bandat_raw.shape[0] / (ptcnt))))
print(ptcnt)
print(bcnt)
# get views of the raw data that are easier to work with
kbandat = bandat_raw[:ptcnt,0] # k point length along path
ebandat = bandat_raw.reshape((bcnt,ptcnt,2))[:,:,1] # band energy # k-points
lines[cnt] = [0]*bcnt # point this list element to another list
for ib in range(bcnt):
#l, = plt.plot(kbandat, ebandat[ib], c=cols[cnt],lw=1.0)
l, = ax.plot(kbandat, ebandat[ib], c=cols[cnt],lw=1.0)
lines[cnt][ib] = l
y0 = 0.03 + 0.07*cnt
bxht = 0.035
axbox1 = plt.axes([0.03, y0, 0.08, bxht]) # x0, y0, width, height
axbox2 = plt.axes([0.13, y0, 0.08, bxht])
txbox1[cnt] = TextBox(axbox1, '', initial=str(1))
txbox2[cnt] = TextBox(axbox2, '', initial=str(bcnt))
txbox1[cnt].on_submit( lambda x: setlines(lines[cnt], x, txbox2[cnt].text) )
txbox2[cnt].on_submit( lambda x: setlines(lines[cnt], txbox1[cnt].text, x) )
axalpha = plt.axes([0.25, y0, 0.65, bxht])
alslid[cnt] = Slider(axalpha, '', 0.1, 1.0, valinit=1.0)
salpha = alslid[cnt]
alslid[cnt].on_changed( lambda x: alphalines(lines[cnt], x) )
#end for cnt, fnam in enumerate(finam):
plt.text(0.01, 1.2, 'Lo Band', transform=axbox1.transAxes)
plt.text(0.01, 1.2, 'Hi Band', transform=axbox2.transAxes)
plt.text(0.01, 1.2, 'Line Opacity', transform=axalpha.transAxes)
plt.show()
All the widgets only control the last data set plotted instead of the individual data sets I tried to associate with each widget. Here is a sample output:
Here the bottom slider should be changing the blue lines' opacity, but instead it changes the red lines' opacity. Originally the variables txbox1, txbox2, and alslid were not lists. I changed them to lists though to ensure they weren't garbage collected but it didn't change anything.
Here is the test data set1 and set2 I've been using. They should be saved as files 'wan_band.dat' and 'wan_band.pwx.dat' as per the hard coded list finam in the code.
I figured it out, using a lambda to partially execute some functions with an iterator value meant they were always being evaluated with the last value of the iterator. Switching to functools.partial fixed the issue.
I am trying to animate a bar chart in Bqplot. I would like to be able to update both the x and y values for the bars and have them adjust smoothly.
The code below behaves as expected for 2 of the 3 bars in my chart, but the 3rd bar is redrawn completely at each timestep.
I was initially trying this with only 2 bars. The first bar behaved as expected, but the 2nd would be redrawn at each timestep. I added the 3rd bar to try solve the problem.
initialIndex = 0
idxSlider3 = IntSlider(min=0, max=20, step=1,
description='Index',value=initialIndex)
''' I want to update the bar chart with this function '''
def update_chart3(change):
with bar3.hold_sync():
bar3.x = [idxSlider3.value,
idxSlider3.value + 1,
idxSlider3.value + 2]
bar3.y = [idxSlider3.value, idxSlider3.value, idxSlider3.value]
idxSlider3.observe(update_chart3, 'value')
fig3 = plt.figure(animation_duration=1000)
bar3 = plt.bar(x=[0, 1, 2], y=[1, 1, 0])
play_button3 = Play(min=0, max=20, step=1, interval=1000, initial_value=0)
jslink((play_button3, 'value'), (idxSlider3, 'value'))
VBox([HBox([idxSlider3, play_button3]), fig3])
Here is a way of making the 'bars' animate nicely in x. It can't be done with bars. Instead I've used line marks - which is a hack. But you get the flexibility. And I prefer using Bqplot in the object model (rather than the pyplot way).
import bqplot as bq
from ipywidgets import *
import numpy as np
initialIndex = 0
xBar=[0, 2, 4]
yBar=[1, 1, 0]
zeroY = 0
barWidth = 1
idxSlider3 = IntSlider(min=0, max=20, step=1,
description='Index',value=initialIndex)
''' I want to update the bar chart with this function '''
def update_chart3(change):
xBar = [idxSlider3.value,
idxSlider3.value + 2,
idxSlider3.value + 4]
np.random.rand()
yBar = [idxSlider3.value + np.random.rand()*2, idxSlider3.value + np.random.rand()*2, idxSlider3.value + np.random.rand()*2]
xList, yList = getLineCoordsFromBarLike(xBar, yBar)
lines.x = xList
lines.y = yList
idxSlider3.observe(update_chart3, 'value')
x_sc = bq.LinearScale()
y_sc = bq.LinearScale()
x_ax1 = bq.Axis(label='', scale=x_sc, num_ticks = 3)
y_ax1 = bq.Axis(label='', scale=y_sc, orientation='vertical')
def getLineCoordsFromBarLike(xBar, yBar):
""" Convert of single list of bar coordinates to a 2D array of line coordinates that describe the rectangular shape
xBar: 1D list of numbers for central x position of bar chart
yBar: 1D list of numbers for amplitudes of bar chart (must be same length as xBar)
retrns x cordinates 2D array, y coordinates 2D array.
"""
xList= []
yList= []
for num, x in enumerate(xBar):
y = yBar[num]
xList.append([x - barWidth/2, x - barWidth/2, x + barWidth/2, x + barWidth/2,])
yList.append([zeroY, y, y, zeroY])
x_ax1.tick_values = xBar
return xList, yList
xList, yList = getLineCoordsFromBarLike(xBar, yBar)
lines = bq.Lines(x=xList, y=yList,
scales={'x': x_sc, 'y': y_sc},
colors=['black'],
display_legend=True,
# tooltip=def_tt,
stroke_width = .5,
close_path = True,
fill = 'inside',
fill_colors = bq.colorschemes.CATEGORY10 * 10
)
margins = dict(top=10, bottom=40, left=50, right=30)
fig3 = bq.Figure(marks=[lines], axes=[x_ax1, y_ax1], fig_margin=margins, animation_duration=1000)
fig3.layout.width = '600px'
fig3.layout.height = '600px'
# def_tt = bq.Tooltip(fields=['name',], formats=['',], labels=['id', ])
play_button3 = Play(min=1, max=20, step=1, interval=1000, initial_value=0)
jslink((play_button3, 'value'), (idxSlider3, 'value'))
VBox([HBox([idxSlider3, play_button3]), fig3])
When you say 'adjust' smoothly, you want the bars to shift to the right, without redrawing? I don't think bqplot 'moves' bars like that. The data for the new bars 1 and 2 already exists (as these were plotted as old bars 2 and 3), so these don't redraw. The new bar 3 data didn't exist before, this needs drawing from scratch. This gives the appearance of 'moving' bars around.
As a different example, watch what happens when you move the bars one unit across, but they are spaced two units apart. You should see all bars draw from scratch each time.
from ipywidgets import *
import bqplot.pyplot as plt
initialIndex = 0
idxSlider3 = IntSlider(min=0, max=20, step=1,
description='Index',value=initialIndex)
''' I want to update the bar chart with this function '''
def update_chart3(change):
with bar3.hold_sync():
bar3.x = [idxSlider3.value,
idxSlider3.value + 2,
idxSlider3.value + 4]
bar3.y = [idxSlider3.value, idxSlider3.value, idxSlider3.value]
idxSlider3.observe(update_chart3, 'value')
fig3 = plt.figure(animation_duration=1000)
bar3 = plt.bar(x=[0, 1, 2], y=[1, 1, 0])
play_button3 = Play(min=1, max=20, step=1, interval=1000, initial_value=0)
jslink((play_button3, 'value'), (idxSlider3, 'value'))
VBox([HBox([idxSlider3, play_button3]), fig3])