Pyplot: changing color depending on class - python

I have an array of values with their associated class labels (0 or 1). I'd like to change the colour of the plotted values based on their class labels.
I'm using the matplotlib.pyplot plot function to plot the values:
plt.plot(data[0])
For each value the associated class labels are stored in an separate array of the same length as the data array.
The current plot looks like this:
The areas in between the red lines should be coloured differently.

You could split it in two different data sets:
xx0 = class_labels == 0
xx1 = class_labels == 1
data_class_0 = data[0].copy()
data_class_0[xx1] = np.nan
data_class_1 = data[0].copy()
data_class_1[xx0] = np.nan
plt.plot(data_class_0, 'b')
plt.plot(data_class_1, 'r')

Related

Placing Labels in nested categorical stacked bar with Bokeh and Pandas

I am trying to replicate a chart like the following using a pandas dataframe and bokeh vbar.:
Objective
So far, I´ve managed to place the labels in their corresponding height but now I can't find a way to access the numeric value where the category (2016,2017,2018) is located in the x axis. This is my result:
My nested categorical stacked bars chart
This is my code. It's messy but it's what i've managed so far. So is there a way to access the numeric value in x_axis of the bars?
def make_nested_stacked_bars(source,measurement,dimension_attr):
#dimension_attr is a list that contains the names of columns in source that will be used as categories
#measurement containes the name of the column with numeric data.
data = source.copy()
#Creates list of values of highest index
list_attr = source[dimension_attr[0]].unique()
list_stackers = list(source[dimension_attr[-1]].unique())
list_stackers.sort()
#trims labals that are too wide to fit in graph
for column in data.columns:
if data[column].dtype.name == 'object':
data[column] = np.where(data[column].apply(len) > 30, data[column].str[:30]+'...', data[column])
#Creates a list of dataframes, each grouping a specific value
list_groups = []
for item in list_attr:
list_groups.append(data[data[dimension_attr[0]] == item])
#Groups data by dimension attrs, aggregates measurement to count
#Drops highest index from dimension attr
dropped_attr = dimension_attr[0]
dimension_attr.remove(dropped_attr)
#Creates groupby by the last 2 parameters, and aggregates to count
#Calculates percentage
for index,value in enumerate(list_groups):
list_groups[index] = list_groups[index].groupby(by=dimension_attr).agg({measurement: ['count']})
list_groups[index] = list_groups[index].groupby(level=0).apply(lambda x: round(100 * x / float(x.sum()),1))
# Resets indexes
list_groups[index] = list_groups[index].reset_index()
list_groups[index] = list_groups[index].pivot(index=dimension_attr[0], columns=dimension_attr[1])
list_groups[index].index = [(x,list_attr[index]) for x in list_groups[index].index]
# Drops dimension attr as top level column
list_groups[index].columns = list_groups[index].columns.droplevel(0)
list_groups[index].columns = list_groups[index].columns.droplevel(0)
df = pd.concat(list_groups)
# Get the number of colors needed for the plot.
colors = brewer["Spectral"][len(list_stackers)]
colors.reverse()
p = figure(plot_width=800, plot_height=500, x_range=FactorRange(*df.index))
renderers = p.vbar_stack(list_stackers, x='index', width=0.3, fill_color=colors, legend=[get_item_value(x)for x in list_stackers], line_color=None, source=df, name=list_stackers,)
# Adds a different hovertool to a stacked bar
#empy dictionary with initial values set to zero
list_previous_y = {}
for item in df.index:
list_previous_y[item] = 0
#loops through bar graphs
for r in renderers:
stack = r.name
hover = HoverTool(tooltips=[
("%s" % stack, "#%s" % stack),
], renderers=[r])
#Initial value for placing label in x_axis
previous_x = 0.5
#Loops through dataset rows
for index, row in df.iterrows():
#adds value of df column to list
list_previous_y[index] = list_previous_y[index] + df[stack][index]
## adds label if value is not nan and at least 10
if not math.isnan(df[stack][index]) and df[stack][index]>=10:
p.add_layout(Label(x=previous_x, y=list_previous_y[index] -df[stack][index]/2,
text='% '+str(df[stack][index]), render_mode='css',
border_line_color='black', border_line_alpha=1.0,
background_fill_color='white', background_fill_alpha=1.0))
# increases position in x_axis
#this should be done by adding the value of next bar in x_axis
previous_x = previous_x + 0.8
p.add_tools(hover)
p.add_tools(hover)
p.legend.location = "top_left"
p.x_range.range_padding = 0.2
p.xgrid.grid_line_color = None
return p
Or is there an easier way to get all this done?
Thank you for your time!
UPDATE:
Added an additional image of a three level nested chart where the label placement in x_axis should be accomplished too
Three level nested chart
I can't find a way to access the numeric value where the category (2016,2017,2018) is located in the x axis.
There is not any way to access this information on the Python side in standalone Bokeh output. The coordinates are only computed inside the browser on the JavaScript side. i.e. only after your Python code has finished running and is out of the picture entirely. Even in a Bokeh server app context there is not any direct way, as there are not any synchronized properties that record the values.
As of Bokeh 1.3.4, support for placing labels with categorical coordinates is a known open issue.
In the mean time, the only workarounds I can suggest are:
Use the text glyph method with coordinates in a ColumnDataSource, instead of Label. That should work to position with actual categorical coordinates. (LabelSet might also work, though I have not tried). You can see an example of text with categorical coordiantes here:
https://github.com/bokeh/bokeh/blob/master/examples/plotting/file/periodic.py
Use numerical coordinates to position the Label. But you will have to experiment/best guess to find numercal coordinates that work for you. A rule of thumb is that categories have a width of 1.0 in synthetic (numeric) coordinate space.
My solution was..
Creating a copy of the dataframe used for making the chart. This dataframe (labeling_data) contains the y_axis coordinates calculated so that the label is positioned at the middle of the corresponding stacked bar.
Then, added aditional columnns to be used as the actual label where the values to be displayed were concatenated with the percentage symbol.
labeling_data = df.copy()
#Cumulative sum of columns
labeling_data = labeling_data.cumsum(axis=1)
#New names for columns
y_position = []
for item in labeling_data.columns:
y_position.append(item+'_offset')
labeling_data.columns = y_position
#Copies original columns
for item in df:
#Adding original columns
labeling_data[item] = df[item]
#Modifying offset columns to place label in the middle of the bar
labeling_data[item+'_offset'] = labeling_data[item+'_offset']-labeling_data[item]/2
#Concatenating values with percentage symbol if at least 10
labeling_data[item+'_label'] = np.where(df[item] >=10 , '% '+df[item].astype(str), "")
Finally, by looping through the renderers of the plot, a labelset was added to each stack group using the labeling_data as Datasource . By doing this, the index of the dataframe can be used to set the x_coordinate of the label. And the corresponding columns were added for the y_coordinate and text parameters.
info = ColumnDataSource(labeling_data)
#loops through bar graphs
for r in renderers:
stack = r.name
#Loops through dataset rows
for index, row in df.iterrows():
#Creates Labelset and uses index, y_offset and label columns
#as x, y and text parameters
labels = LabelSet(x='index', y=stack+'_offset', text=stack+'_label', level='overlay',
x_offset=-25, y_offset=-5, source=info)
p.add_layout(labels)
Final result:
Nested categorical stacked bar chart with labels

How do I label a specific point in a scatter plot with a unique ID?

I am creating an interactive graph for a layout that looks a lot like this:
Each point has a unique ID and is usually part of a group. Each group has their own color so I use multiple scatter plots to create the entire layout. I need the following to occur when I click on a single point:
On mouse click, retrieve the ID of the selected point.
Plug the ID into a black box function that returns a list of nearby* IDs.
Highlight the points of the IDs in the returned list.
*It is possible for some of the IDs to be from different groups/plots.
How do I:
Associate each point with an ID and return the ID when the point is clicked?
Highlight other points in the layout when all I know is their IDs?
Re-position individual points while maintaining their respective groups i.e. swapping positions with points that belong to different groups/plots.
I used pyqtgraph before switching over to matplotlib so I first thought of creating a dictionary of IDs and their point objects. After experimenting with pick_event, it seems to me that the concept of point objects does not exist in matplotlib. From what I've learned so far, each point is represented by an index and only its PathCollection can return information about itself e.g. coordinates. I also learned that color modification of a specific point is done through its PathCollection whereas in pyqtgraph I can do it through a point object e.g. point.setBrush('#000000').
I am still convinced that using a single scatter plot would be the much better option. There is nothing in the question that would contradict that.
You can merge all your data in a single DataFrame, with columns group, id, x, y, color. The part in the code below which says "create some dataset" does create such a DataFrame
group id x y color
0 1 AEBB 0 0 palegreen
1 3 DCEB 1 0 plum
2 0 EBCC 2 0 sandybrown
3 0 BEBE 3 0 sandybrown
4 3 BEBB 4 0 plum
Note that each group has its own color. One can then create a scatter from it, using the colors from the color column.
A pick event is registered as in this previous question and once a point is clicked, which is not already black, the id from the DataFrame corresponding to the selected point is obtained. From the id, other ids are generated via the "blackbox function" and for each id obtained that way the respective index of the point in the dataframe is determined. Because we have single scatter this index is directly the index of the point in the scatter (PathCollection) and we can paint it black.
import numpy as np; np.random.seed(1)
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.colors
### create some dataset
x,y = np.meshgrid(np.arange(20), np.arange(20))
group = np.random.randint(0,4,size=20*20)
l = np.array(np.meshgrid(list("ABCDE"),list("ABCDE"),
list("ABCDE"),list("ABCDE"))).T.reshape(-1,4)
ide = np.random.choice(list(map("".join, l)), size=20*20, replace=False)
df = pd.DataFrame({"id" : ide, "group" : group ,
"x" : x.flatten(), "y" : y.flatten() })
colors = ["sandybrown", "palegreen", "paleturquoise", "plum"]
df["color"] = df["group"]
df["color"].update(df["color"].map(dict(zip(range(4), colors ))))
print df.head()
### plot a single scatter plot from the table above
fig, ax = plt.subplots()
scatter = ax.scatter(df.x,df.y, facecolors=df.color, s=64, picker=4)
def getOtherIDsfromID(ID):
""" blackbox function: create a list of other IDs from one ID """
l = [np.random.permutation(list(ID)) for i in range(5)]
return list(set(map("".join, l)))
def select_point(event):
if event.mouseevent.button == 1:
facecolor = scatter._facecolors[event.ind,:]
if (facecolor == np.array([[0, 0, 0, 1]])).all():
c = df.color.values[event.ind][0]
c = matplotlib.colors.to_rgba(c)
scatter._facecolors[event.ind,:] = c
else:
ID = df.id.values[event.ind][0]
oIDs = getOtherIDsfromID(ID)
# for each ID obtained, make the respective point black.
rows = df.loc[df.id.isin([ID] + oIDs)]
for i, row in rows.iterrows():
scatter._facecolors[i,:] = (0, 0, 0, 1)
tx = "You selected id {}.\n".format(ID)
tx += "Points with other ids {} will be affected as well"
tx = tx.format(oIDs)
print tx
fig.canvas.draw_idle()
fig.canvas.mpl_connect('pick_event', select_point)
plt.show()
In the image below, the point with id DAEE has been clicked on, and other points with ids ['EDEA', 'DEEA', 'EDAE', 'DEAE'] have been chosen by the blackbox function. Not all of those IDs exist, such that two other points with an existing id are colorized as well.

Scatterplot: different colour & annotation for each observation depending on previous untransformed dataset PCA matplotlib python

I'm implementing a PCA on the following data (provided in code). I choose 2 components which gives me output in the form [x1, y1], [x2, y2], etc.
I then want to plot these two PCs (a) on a plot (as shown below the code) however I want to colour code them according to the letter in the untransformed data (data). i.e. observation [x1, y1] is originally assigned as "A" therefore I want that to be a different colour to those with corresponding "B" and "C" labels. I think a dictionary is appropriate but not sure how to link the original dataset to the new PCA variables.
I also want to annotate these points (from a) with the names in the original set (data), i.e. [x1, y1] would be annotated with "John".
Any help is greatly appreciated.
# load packages
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import scale
from sklearn.decomposition import PCA
# load data
data = np.array([["John","A",1,2,1,3,4,6],
["Julie","A",3,1,2,2,2,4],
["James","B",2,4,1,1,2,5],
["Jemma","C",3,5,1,2,3,2],
["Jet","B",1,3,2,1,1,3],
["Jane","A",2,4,2,1,3,4]])
# feature array & scale
y = data[:,[2,3,4,5,6,7]]
z = scale(y)
# PCA
pca = PCA(n_components=6)
pca.fit(z)
# scree plot
var = pca.explained_variance_ratio_
var1 = np.cumsum(np.round(pca.explained_variance_ratio_, decimals=4)*100)
#print(var1)
#plt.plot(var1)
#plt.show()
# PCA w/ 2 components
pca = PCA(n_components=2)
pca.fit(z)
a = pca.fit_transform(z)
# colour map **HELP**
#colours = {"A":"red", "B":"green", "C":"blue"}
# annotation **HELP**
# scatter plot
plt.scatter(a[:,0],a[:,1])
plt.show()
EDIT:
colour problem SOLVED
annotation problem NEED HELP:
names = [rows[0] for rows in data]
plt.scatter(a[:,0], a[:,1], c=point_colours)
plt.annotate(names, (a[:,0], a[:,1]))
same problem when coding as:
for i in names:
plt.annotate(names, (a[:,0], a[:,1]))
although print names outputs the names i want to annotate, it does not show up on the plot. I have tried using both names and str(names) in the annotate parameters but keep getting
TypeError: only length-1 arrays can be converted to Python scalars
and then the graph is outputted without labels.
any ideas?
Something like:
point_colors = [colours[row[1]] for row in data]
plt.scatter(a[:,0], a[:,1], c=point_colors)
it creates a list with the color of points.
For the annotation:
for i, row in enumerate(data):
xy = (a[:,0][i], a[:,1][i])
name = data[i][0]
plt.annotate(name, xy=xy)
You should move xy to avoid the overlap of the text with the point.

Delete points in scatter plot

I plotted a scatter plot using python by importing data from text files and I want to delete points with x axis values 0. This is the program I have written
mat0 = genfromtxt("herbig0.txt");
mat1 = genfromtxt("coup1.txt");
pyplot.xlim([-2,6])
pyplot.ylim([26,33])
colors=['red', 'blue','green']
pyplot.scatter(mat0[:,13], mat0[:,4], label = "herbig stars", color=colors[0]);
if mat1[:,2] != 0:
pyplot.scatter(mat1[:,2], mat1[:,9], label = "COUP data of SpT F5-M6 ", color=colors[1]);
pyplot.scatter(mat1[:,2], mat1[:,10], label = "COUP data of SpT B0-F5", color=colors[2]);
pyplot.legend();
pyplot.xlabel('Log(Lbol) (sol units)')
pyplot.ylabel('Log(Lx) (erg/s)')
pyplot.title('Lx vs Lbol')
pyplot.show();
This is my output graph when I don't use the if statements.
I want to delete all the blue points which have an x axis value of zero. Please suggest changes. If I use the if statement and all the points vanished.
As your data is stored in numpy arrays you could always just filter them out:
Using either nonzero, or setting some small threshhold value that you filter out:
#Either
mat_filter = np.nonzero(mat1[:,2])
#or
mat_filter = np.abs(mat1[:,2])>1e-12
Then you can use that filter on the affected arrays:
mat1mod2 = mat1[:,2][mat_filter]
mat1mod9 = mat1[:,9][mat_filter]
mat1mod10 = mat1[:,10][mat_filter]
And plot them instead of the original arrays.

How do I plot observations each with multiple values in python?

I have data for each individual participant from a survey. Each individual has a vector of data for example :
#[a,b,c]
[1,2,5] # 1 participant
...
...
...
[1,3,4]
Instead of having that kind of data, I have the data column wise. Example :
a = [1...1] # has n values equal to participants
b = [2...3] # has n values equal to participants
c = [5...4] # has n values equal to participants
I need to plot this data somehow to represent it clearly as a figure, does anybody have ideas how to plot this all together? I have plotted them individually as bar plots with frequencies, but I would like them to be plotted together as a 3D plot so that all 3 dimension's values can be inferred from the data.
I have around 200 participants.
Any suggestions are welcome.
Use each list as xaxis, yaxis, and zaxis data. This is especially useful when you know the lists are the same length, and each column represents one object. For example, (a[0], b[0], c[0]) represent a trait of the same object. The a-, b- and c-list objects represent the x-, -y, and z-axis fields, respectively.
If you're trying to do a Scatter plot, for example:
import plotly as plotly
from plotly.graph_objs import *
# stuff here, i.e. your code
myScatter = Scatter3D(
# some graph stuff, like your title:
# title = 'Random_Plot_Title'
x = a,
y = b,
z = c,
# some more stuff: Here's what I tend to add
# mode = 'markers',
# marker = dict(
# color = '#DC6D37'
# ),
# name = 'Your_Legend_Name_Here',
# legendgroup = 'Group_Multiple_Traces_Here',
)

Categories

Resources