How to plot multiple colour on ylable using matplotlib? - matplotlib

I have list of data want to plot on a subplot. Then I want to lable ylable with different set of colour. See the simple code example below:-
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('yellow red blue')
plt.show()
This produces the following image:-
In the resultant image ylable is named as 'yellow red blue' and all in black colour. But I would like to have this label coloured like this:-
'yellow' with yellow colour,
'red' with red colour
and 'blue' with blue colour.
Is it possible with matplotlib?

No. You can't do this with a single text object. You could manually add three different labels, i.e.:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
ax = plt.gca()
ax.text(-0.1, 0.4, 'yellow', color='yellow', rotation=90, transform=ax.transAxes)
ax.text(-0.1, 0.5, 'red', color='red', rotation=90, transform=ax.transAxes)
ax.text(-0.1, 0.6, 'blue', color='blue', rotation=90, transform=ax.transAxes)
plt.show()

Related

Setting a list of colors for a linechart with matplotlib.pyplot

I have a line chart with six lines. My goal is to set each of those lines with a particular color:
['304558', 'FE9235', '526683', 'FE574B ', 'FFD104', '6BDF9C'] or
['darkblue', 'orange', 'skyblue', 'red ', 'yellow', 'lightgreen']
However, in my code I only managed to choose a particular colormap ('Set1'). How can I change this for my list of colors? Below you will find my code.
Thank you very much! I am really in a hurry
plt.style.use('seaborn-darkgrid')
palette = plt.get_cmap('Set1')
num=0
for column in df_corb.drop('month_year', axis=1):
num+=1
plt.plot(df_corb['month_year'], df_corb[column], marker='', color=palette(num),
linewidth=1, alpha=0.9, label=column)
plt.xticks(rotation=45)
plt.legend(loc=0, prop={'size': 9},bbox_to_anchor=(1.05, 1.0), title='Key Words')
plt.title("Frequency of key words in Corbeau News ", loc='left', fontsize=12, fontweight=0, color='orange')
plt.xlabel("Time")
plt.ylabel("Percentage")
plt.savefig('Time\Corbeau_frequency_1.png',dpi=300, bbox_inches='tight')

Errorbar plot with different color on each marker

I can create an errorbar plot with:
import matplotlib.pyplot as plt
import pandas as pd
data = {'x': [194.33, 281.0, 317.5, 118.66666666666667, 143.0],
'y': [292.83, 284.45, 302.47, 178.8, 165.81],
'error':[191.83094965214667, 188.15999999999997, 170.51999999999998, 35.951147099609756, 27.439999999999998],
'color': ['yellow','red','red','yellow','red']}
# x y error color
#194.330000 292.83 191.830950 yellow
#281.000000 284.45 188.160000 red
#317.500000 302.47 170.520000 red
#118.666667 178.80 35.951147 yellow
#143.000000 165.81 27.440000 red
df = pd.DataFrame(data)
fig, ax = plt.subplots()
ax.errorbar(x=df['x'], y=df['y'], yerr=df['error'], fmt='o', ecolor='black', elinewidth=1, capsize=5, c='blue')
But I want to color each each observation (blue dot) using my color column, but this doesnt work. Is there some way?
ax.errorbar(x=df['x'], y=df['y'], yerr=df['error'], fmt='o', ecolor='black', elinewidth=1, capsize=5, c=df['color'])
ValueError: RGBA sequence should have length 3 or 4
Unfortunately, this doesn't work (see a discussion here on github).
You can solve this by using a loop, and plotting them one by one:
for x, y, err, colors in zip(df['x'], df['y'], df['error'], df['color']):
ax.errorbar(x=x, y=y, yerr=err, fmt='o', ecolor='black', elinewidth=1, capsize=5, color = colors)

Errorbar plot transparency overlapping

In an errorbar matplotlib plot, the main line, the markers and the errorbars of a same color overlap each other on their countour when I use the alpha parameter. Although my goal was to have a transparency between the two different colors, but not within the same color, as if same color lines, markers and errorbars were only one object. Is that possible?
import matplotlib.pyplot as plt
import numpy as np
Time = np.array([1, 2, 3])
Green = np.array([3, 5, 9])
Blue = np.array([4, 7, 13])
Green_StDev = np.array([0.6, 0.6, 0.7])
Blue_StDev = np.array([0.5, 0.5, 0.6])
plt.errorbar(Time, Green, Green_StDev, marker='o', c='green', alpha=0.5)
plt.errorbar(Time, Blue, Blue_StDev, marker='o', c='blue', alpha=0.5)
plt.show()
Like the example below, but with transparency only between different color objects, differently of the example above.
I think you cannot draw them as one single object since they (marker and error bar) are drawn individually. However, to make it more 'aesthetic', you could redraw a non-transparent marker:
import matplotlib.pyplot as plt
import numpy as np
Time = np.array([1, 2, 3])
Green = np.array([3, 5, 9])
Blue = np.array([4, 7, 13])
Green_StDev = np.array([0.6, 0.6, 0.7])
Blue_StDev = np.array([0.5, 0.5, 0.6])
plt.errorbar(Time, Green, Green_StDev, marker='o', c='green', alpha=0.5)
# Add additional marker
plt.scatter(Time, Green,marker='o', c='green')
plt.errorbar(Time, Blue, Blue_StDev, marker='o', c='blue', alpha=0.5)
# Add additional marker
plt.scatter(Time, Blue, marker='o', c='blue')
plt.show()

matplotlib line plot dont show vertical lines in step function

I do have a plot that only consists of horizontal lines at certain values when I have a signal, otherwise none. So, I am looking for a way to plot this without the vertical lines. there may be gaps between the lines when there is no signal and I dont want the lines to connect nor do I want a line falling off to 0. Is there a way to plot this like that in matplotlib?
self.figure = plt.figure()
self.canvas = FigureCanvas(self.figure)
axes = self.figure.add_subplot(111)
axes.plot(df.index, df["x1"], lw=1.0, c=self.getColour('g', i), ls=ls)
The plot you are looking for is Matplotlib's plt.hlines(y, xmin, xmax).
For example:
import matplotlib.pyplot as plt
y = range(1, 11)
xmin = range(10)
xmax = range(1, 11)
colors=['blue', 'green', 'red', 'yellow', 'orange', 'purple',
'cyan', 'magenta', 'pink', 'black']
fig, ax = plt.subplots(1, 1)
ax.hlines(y, xmin, xmax, colors=colors)
plt.show()
Yields a plot like this:
See the Matplotlib documentation for more details.

Axis labels on invisible axes in matplotlib

Is it possible to have a visible axis label on an invisble axis? I would like to plot 2 axes that have, apart from their own ylabels, also a common one:
import matplotlib
from matplotlib.pyplot import *
figure()
ax1 = axes([0.3, 0.2, 0.4, 0.2]); ylabel("Label 1")
ax2 = axes([0.3, 0.5, 0.4, 0.2]); ylabel("Label 2")
ax_common = axes([0.2, 0.2, 0.5, 0.5], zorder=-10)
xticks([]); yticks([])
ylabel("Common", fontsize="x-large")
savefig("out.png")
The code above produces this plot:
out.png
Is there a way to remove axis lines? If I add ax_common.set_axis_off(), the axes and the ylabel is removed. Do I have to create a text label instead, without create the additional axes?
Do this:
ax_common.set_frame_on(False)