Plot string values in matplotlib - python

I am using matplotlib for a graphing application. I am trying to create a graph which has strings as the X values. However, the using plot function expects a numeric value for X.
How can I use string X values?

From matplotlib 2.1 on you can use strings in plotting functions.
import matplotlib.pyplot as plt
x = ["Apple", "Banana", "Cherry"]
y = [5,2,3]
plt.plot(x, y)
plt.show()
Note that in order to preserve the order of the input strings on the plot you need to use matplotlib >=2.2.

You should try xticks
import pylab
names = ['anne','barbara','cathy']
counts = [3230,2002,5456]
pylab.figure(1)
x = range(3)
pylab.xticks(x, names)
pylab.plot(x,counts,"g")
pylab.show()

Why not just make the x value some auto-incrementing number and then change the label?
--jed

Here's one way which i know works, though i would think creating custom symbols is a more natural way accomplish this.
from matplotlib import pyplot as PLT
# make up some data for this example
t = range(8)
s = 7 * t + 5
# make up some data labels which we want to appear in place of the symbols
x = 8 * "dp".split()
y = map(str, range(8))
data_labels = [ i+j for i, j in zip(x, y)]
fig = PLT.figure()
ax1 = fig.add_subplot(111)
ax1.plot(t, s, "o", mfc="#FFFFFF") # set the symbol color so they are invisible
for a, b, c in zip(t, s, data_labels) :
ax1.text(a, b, c, color="green")
PLT.show()
So this puts "dp1", "dp2",... in place of each of the original data symbols--in essence creating custom "text symbols" though again i have to believe there's a more direct way to do this in matplotlib (without using Artists).

I couldn't find a convenient way to accomplish that, so I resorted to this little helper function.
import matplotlib.pyplot as p
def plot_classes(x, y, plotfun=p.scatter, **kwargs):
from itertools import count
import numpy as np
classes = sorted(set(x))
class_dict = dict(zip(classes, count()))
class_map = lambda x: class_dict[x]
plotfun(map(class_map, x), y, **kwargs)
p.xticks(np.arange(len(classes)), classes)
Then, calling plot_classes(data["class"], data["y"], marker="+") should work as expected.

Related

How to use pandas with matplotlib to create 3D plots

I am struggling a bit with the pandas transformations needed to make data render in 3D on matplot lib. The data I have is usually in columns of numbers (usually time and some value). So lets create some test data to illustrate.
import pandas as pd
pattern = ("....1...."
"....1...."
"..11111.."
".1133311."
"111393111"
".1133311."
"..11111.."
"....1...."
"....1....")
# create the data and coords
Zdata = list(map(lambda d:0 if d == '.' else int(d), pattern))
Zinverse = list(map(lambda d:1 if d == '.' else -int(d), pattern))
Xdata = [x for y in range(1,10) for x in range(1,10)]
Ydata = [y for y in range(1,10) for x in range(1,10)]
# pivot the data into columns
data = [d for d in zip(Xdata,Ydata,Zdata,Zinverse)]
# create the data frame
df = pd.DataFrame(data, columns=['X','Y','Z',"Zi"], index=zip(Xdata,Ydata))
df.head(5)
Edit: This block of data is demo data that would normally come from a query on a
database that may need more cleaning and transforms before plotting. In this case data is already aligned and there are no problems aside having one more column we don't need (Zi).
So the numbers in pattern are transferred into height data in the Z column of df ('Zi' being the inverse image) and with that as the data frame I've struggled to come up with this pivot method which is 3 separate operations. I wonder if that can be better.
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.cm as cm
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
Xs = df.pivot(index='X', columns='Y', values='X').values
Ys = df.pivot(index='X', columns='Y', values='Y').values
Zs = df.pivot(index='X', columns='Y', values='Z').values
ax.plot_surface(Xs,Ys,Zs, cmap=cm.RdYlGn)
plt.show()
Although I have something working I feel there must be a better way than what I'm doing. On a big data set I would imagine doing 3 pivots is an expensive way to plot something. Is there a more efficient way to transform this data ?
I guess you can avoid some steps during the preparation of the data by not using pandas (but only numpy arrays) and by using some convenience fonctions provided by numpy such as linespace and meshgrid.
I rewrote your code to do so, trying to keep the same logic and the same variable names :
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
pattern = ("....1...."
"....1...."
"..11111.."
".1133311."
"111393111"
".1133311."
"..11111.."
"....1...."
"....1....")
# Extract the value according to your logic
Zdata = list(map(lambda d:0 if d == '.' else int(d), pattern))
# Assuming the pattern is always a square
size = int(len(Zdata) ** 0.5)
# Create a mesh grid for plotting the surface
Xdata = np.linspace(1, size, size)
Ydata = np.linspace(1, size, size)
Xs, Ys = np.meshgrid(Xdata, Ydata)
# Convert the Zdata to a numpy array with the appropriate shape
Zs = np.array(Zdata).reshape((size, size))
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Plot the surface
ax.plot_surface(Xs, Ys, Zs, cmap=cm.RdYlGn)
plt.show()

How to make the function line break without manually def a piecewise function? [duplicate]

I am using matplotlib to plot some step functions from a dataframe
df['s1'].plot(c='b', drawstyle="steps-post")
df['s2'].plot(c='b', drawstyle="steps-post")
...
The result looks like
I would like to have this only plot the horizontal lines, not the vertical lines connecting the jump points. I could not find a straightforward parameter for plot that would seem to do that. Is there a way to do this?
There is no built-in option to produce a step function without vertical lines as far as I can tell. But you may easily build one yourself. The following uses the fact that np.nan is not plotted and cuts the line. So adding np.nan in between the steps suppresses the vertical line.
import matplotlib.pyplot as plt
import numpy as np
def mystep(x,y, ax=None, where='post', **kwargs):
assert where in ['post', 'pre']
x = np.array(x)
y = np.array(y)
if where=='post': y_slice = y[:-1]
if where=='pre': y_slice = y[1:]
X = np.c_[x[:-1],x[1:],x[1:]]
Y = np.c_[y_slice, y_slice, np.zeros_like(x[:-1])*np.nan]
if not ax: ax=plt.gca()
return ax.plot(X.flatten(), Y.flatten(), **kwargs)
x = [1,3,4,5,8,10,11]
y = [5,4,2,7,6,4,4]
mystep(x,y, color="crimson")
plt.show()
Seems like hlines is the "correct" (built-in) way to do this:
import matplotlib.pyplot as plt
x = [1,3,4,5,8,10,11]
y = [5,4,2,7,6,4]
plt.hlines(y,x[:-1],x[1:])
plt.show()

How to adjust branch lengths of dendrogram in matplotlib (like in astrodendro)? [Python]

Here is my resulting plot below but I would like it to look like the truncated dendrograms in astrodendro such as this:
There is also a really cool looking dendrogram from this paper that I would like to recreate in matplotlib.
Below is the code for generating an iris data set with noise variables and plotting the dendrogram in matplotlib.
Does anyone know how to either: (1) truncate the branches like in the example figures; and/or (2) to use astrodendro with a custom linkage matrix and labels?
import pandas as pd
import numpy as np
from sklearn.datasets import load_iris
import astrodendro
from scipy.cluster.hierarchy import dendrogram, linkage
from scipy.spatial import distance
def iris_data(noise=None, palette="hls", desat=1):
# Iris dataset
X = pd.DataFrame(load_iris().data,
index = [*map(lambda x:f"iris_{x}", range(150))],
columns = [*map(lambda x: x.split(" (cm)")[0].replace(" ","_"), load_iris().feature_names)])
y = pd.Series(load_iris().target,
index = X.index,
name = "Species")
c = map_colors(y, mode=1, palette=palette, desat=desat)#y.map(lambda x:{0:"red",1:"green",2:"blue"}[x])
if noise is not None:
X_noise = pd.DataFrame(
np.random.RandomState(0).normal(size=(X.shape[0], noise)),
index=X_iris.index,
columns=[*map(lambda x:f"noise_{x}", range(noise))]
)
X = pd.concat([X, X_noise], axis=1)
return (X, y, c)
def dism2linkage(DF_dism, method="ward"):
"""
Input: A (m x m) dissimalrity Pandas DataFrame object where the diagonal is 0
Output: Hierarchical clustering encoded as a linkage matrix
Further reading:
http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.cluster.hierarchy.linkage.html
https://pypi.python.org/pypi/fastcluster
"""
#Linkage Matrix
Ar_dist = distance.squareform(DF_dism.as_matrix())
return linkage(Ar_dist,method=method)
# Get data
X_iris_with_noise, y_iris, c_iris = iris_data(50)
# Get distance matrix
df_dism = 1- X_iris_with_noise.corr().abs()
# Get linkage matrix
Z = dism2linkage(df_dism)
#Create dendrogram
with plt.style.context("seaborn-white"):
fig, ax = plt.subplots(figsize=(13,3))
D_dendro = dendrogram(
Z,
labels=df_dism.index,
color_threshold=3.5,
count_sort = "ascending",
#link_color_func=lambda k: colors[k]
ax=ax
)
ax.set_ylabel("Distance")
I'm not sure this really constitutes a practical answer, but it does allow you to generate dendrograms with truncated hanging lines. The trick is to generate the plot as normal, then manipulate the resulting matplotlib plot to recreate the lines.
I couldn't get your example to work locally, so I've just created a dummy dataset.
from matplotlib import pyplot as plt
from scipy.cluster.hierarchy import dendrogram, linkage
import numpy as np
a = np.random.multivariate_normal([0, 10], [[3, 1], [1, 4]], size=[5,])
b = np.random.multivariate_normal([0, 10], [[3, 1], [1, 4]], size=[5,])
X = np.concatenate((a, b),)
Z = linkage(X, 'ward')
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
dendrogram(Z, ax=ax)
The resulting plot is the usual long-arm dendrogram.
Now for the more interesting bit. A dendrogram is made up of a number of LineCollection objects (one for each colour). To update the lines we iterate through these, extracting the details about their constituent paths, modifying these to remove any lines reaching to a y of zero, and then recreating a LineCollection for these modified paths.
The updated path is then added to the axes, and the original is removed.
The one tricky part is determining what height to draw to instead of zero. Since we are iterating over each dendrograms path, we don't know which point came before — we basically have no idea where we are. However, we can exploit the fact that hanging lines hang vertically. Assuming there are no lines on the same x, we can look for the known other y values for a given x and use that as the basis for our new y when calculating. The downside is that in order to make sure we have this number, we have to pre-scan the data.
Note: If you can get dendrogram hanging lines on the same x, you would need to include the y and search for nearest y above this x to do this.
import numpy as np
from matplotlib.path import Path
from matplotlib.collections import LineCollection
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
dendrogram(Z, ax=ax);
for c in ax.collections[:]: # use [:] to get a copy, since we're adding to the same list
paths = []
for path in c.get_paths():
segments = []
y_at_x = {}
# Pre-pass over all elements, to find the lowest y value at each x value.
# we can use this to caculate where to cut our lines.
for n, seg in enumerate(path.iter_segments()):
x, y = seg[0]
# Don't store if the y is zero, or if it's higher than the current low.
if y > 0 and y < y_at_x.get(x, np.inf):
y_at_x[x] = y
for n, seg in enumerate(path.iter_segments()):
x, y = seg[0]
if y == 0:
# If we know the last y at this x, use it - 0.5, limit > 0
y = max(0, y_at_x.get(x, 0) - 0.5)
segments.append([x,y])
paths.append(segments)
lc = LineCollection(paths, colors=c.get_colors()) # Recreate a LineCollection with the same params
ax.add_collection(lc)
ax.collections.remove(c) # Remove the original LineCollection
The resulting dendrogram looks like this:

Plot multiple bars for categorical data

I'm looking for a way to plot multiple bars per value in matplotlib. For numerical data, this can be achieved be adding an offset to the X data, as described for example here:
import numpy as np
import matplotlib.pyplot as plt
X = np.array([1,3,5])
Y = [1,2,3]
Z = [2,3,4]
plt.bar(X - 0.4, Y) # offset of -0.4
plt.bar(X + 0.4, Z) # offset of 0.4
plt.show()
plt.bar() (and ax.bar()) also handle categorical data automatically:
X = ['A','B','C']
Y = [1,2,3]
plt.bar(X, Y)
plt.show()
Here, it is obviously not possible to add an offset, as the categories are not directly associated with a value on the axis. I can manually assign numerical values to the categories and set labels on the x axis with plt.xticks():,
X = ['A','B','C']
Y = [1,2,3]
Z = [2,3,4]
_X = np.arange(len(X))
plt.bar(_X - 0.2, Y, 0.4)
plt.bar(_X + 0.2, Z, 0.4)
plt.xticks(_X, X) # set labels manually
plt.show()
However, I'm wondering if there is a more elegant way that makes use of the automatic category handling of bar(), especially if the number of categories and bars per category is not known in before (this causes some fiddling with the bar widths to avoid overlaps).
There is no automatic support of subcategories in matplotlib.
Placing bars with matplotlib
You may go the way of placing the bars numerically, like you propose yourself in the question. You can of course let the code manage the unknown number of subcategories.
import numpy as np
import matplotlib.pyplot as plt
X = ['A','B','C']
Y = [1,2,3]
Z = [2,3,4]
def subcategorybar(X, vals, width=0.8):
n = len(vals)
_X = np.arange(len(X))
for i in range(n):
plt.bar(_X - width/2. + i/float(n)*width, vals[i],
width=width/float(n), align="edge")
plt.xticks(_X, X)
subcategorybar(X, [Y,Z,Y])
plt.show()
Using pandas
You may also use pandas plotting wrapper, which does the work of figuring out the number of subcategories. It will plot one group per column of a dataframe.
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
X = ['A','B','C']
Y = [1,2,3]
Z = [2,3,4]
df = pd.DataFrame(np.c_[Y,Z,Y], index=X)
df.plot.bar()
plt.show()

Matplotlib pyplot axes formatter

I have an image:
Here in the y-axis I would like to get 5x10^-5 4x10^-5 and so on instead of 0.00005 0.00004.
What I have tried so far is:
fig = plt.figure()
ax = fig.add_subplot(111)
y_formatter = matplotlib.ticker.ScalarFormatter(useOffset=True)
ax.yaxis.set_major_formatter(y_formatter)
ax.plot(m_plot,densities1,'-ro',label='0.0<z<0.5')
ax.plot(m_plot,densities2, '-bo',label='0.5<z<1.0')
ax.legend(loc='best',scatterpoints=1)
plt.legend()
plt.show()
This does not seem to work. The document page for tickers does not seem to provide a direct answer.
You can use matplotlib.ticker.FuncFormatter to choose the format of your ticks with a function as shown in the example code below. Effectively all the function is doing is converting the input (a float) into exponential notation and then replacing the 'e' with 'x10^' so you get the format that you want.
import matplotlib.pyplot as plt
import matplotlib.ticker as tick
import numpy as np
x = np.linspace(0, 10, 1000)
y = 0.000001*np.sin(10*x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y)
def y_fmt(x, y):
return '{:2.2e}'.format(x).replace('e', 'x10^')
ax.yaxis.set_major_formatter(tick.FuncFormatter(y_fmt))
plt.show()
If you're willing to use exponential notation (i.e. 5.0e-6.0) however then there is a much tidier solution where you use matplotlib.ticker.FormatStrFormatter to choose a format string as shown below. The string format is given by the standard Python string formatting rules.
...
y_fmt = tick.FormatStrFormatter('%2.2e')
ax.yaxis.set_major_formatter(y_fmt)
...
Just a brief modification to the solution for better string formatting: I would recommend changing the format function to include latex formatting:
def y_fmt(x, y):
return '${:2.1e}'.format(x).replace('e', '\\cdot 10^{') + '}$'

Categories