How do I align gridlines for two y-axis scales?

I am not sure if this is the prettiest way to do it, but it does fix it with one line: import matplotlib.pyplot as plt import seaborn as sns import numpy as np import pandas as pd np.random.seed(0) fig = plt.figure() ax1 = fig.add_subplot(111) ax1.plot(pd.Series(np.random.uniform(0, 1, size=10))) ax2 = ax1.twinx() ax2.plot(pd.Series(np.random.uniform(10, 20, size=10)), color=”r”) # … Read more

My matplotlib.pyplot legend is being cut off

Eventhough that it is late, I want to refer to a nice recently introduced alternative: New matplotlib feature: The tight bounding box If you are interested in the output file of plt.savefig: in this case the flag bbox_inches=”tight” is your friend! import matplotlib.pyplot as plt fig = plt.figure(1) plt.plot([1, 2, 3], [1, 0, 1], label=”A”) … Read more

How to pick a new color for each plotted line within a figure

I usually use the second one of these: from matplotlib.pyplot import cm import numpy as np #variable n below should be number of curves to plot #version 1: color = cm.rainbow(np.linspace(0, 1, n)) for i, c in zip(range(n), color): plt.plot(x, y, c=c) #or version 2: color = iter(cm.rainbow(np.linspace(0, 1, n))) for i in range(n): c … Read more

How to plot a scatter plot with a legend label for each class

Actually both linked questions provide a way how to achieve the desired result. The easiest method is to create as many scatter plots as unique classes exist and give each a single color and legend entry. import matplotlib.pyplot as plt x=[1,2,3,4] y=[5,6,7,8] classes = [2,4,4,2] unique = list(set(classes)) colors = [ for i in unique] … Read more

Scatter plot with legend for each color in c

First, I have a feeling you meant to use apostrophes, not backticks when declaring colours. For a legend you need some shapes as well as the classes. For example, the following creates a list of rectangles called recs for each colour in class_colours. import matplotlib.patches as mpatches classes = [‘A’,’B’,’C’] class_colours = [‘r’,’b’,’g’] recs = … Read more

How to place inline labels in a line plot

Update: User cphyc has kindly created a Github repository for the code in this answer (see here), and bundled the code into a package which may be installed using pip install matplotlib-label-lines. Pretty Picture: In matplotlib it’s pretty easy to label contour plots (either automatically or by manually placing labels with mouse clicks). There does … Read more