Draw semicircle chart using matplotlib - matplotlib

Is matplotlib capable of creating semicircle charts like this:
I have tried matplotlib.pyplot.pie without success.

It doesn't seem like there is a built-in half-circle type in matplotlib. However, a workaround can be made based on matplotlib.pyplot.pie:
Append the total sum of the data and assign white color to it.
Overlay a white circle in the center by an Artist object (reference).
Sample Code:
import matplotlib.pyplot as plt
# data
label = ["A", "B", "C"]
val = [1,2,3]
# append data and assign color
label.append("")
val.append(sum(val)) # 50% blank
colors = ['red', 'blue', 'green', 'white']
# plot
fig = plt.figure(figsize=(8,6),dpi=100)
ax = fig.add_subplot(1,1,1)
ax.pie(val, labels=label, colors=colors)
ax.add_artist(plt.Circle((0, 0), 0.6, color='white'))
fig.show()
Output:

My solution:
import matplotlib.pyplot as plt
# data
label = ["A", "B", "C"]
val = [1,2,3]
# append data and assign color
label.append("")
val.append(sum(val)) # 50% blank
colors = ['red', 'blue', 'green', 'k']
# plot
plt.figure(figsize=(8,6),dpi=100)
wedges, labels=plt.pie(val, wedgeprops=dict(width=0.4,edgecolor='w'),labels=label, colors=colors)
# I tried this method
wedges[-1].set_visible(False)
plt.show()
Output:
enter image description here

Related

Some concerns with axes.annotate()

Bonjour, I can't enlarge the dimensions of the graph from the moment I
use "axes.annotate()".
Whatever the values of "plt.figure(figsize=(8, 6))", it is the same.
The dimensions do not change. I must make a mistake somewhere...
# Importing libraries for dataframe creation
# and graph plotting
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Creating our own dataframe
data = {"Name": ["Alex", "Bob", "Clarein", "Dexter"],
"Marks": [45, 23, 78, 65]}
# Now convert this dictionary type data into a pandas dataframe
# specifying what are the column names
df = pd.DataFrame(data, columns=['Name', 'Marks'])
print(df.head())
#Defining the plotsize
plt.figure(figsize=(8, 6))
figure, axes = plt.subplots()
plt.bar(df.Name, df.Marks, color = 'c', width = 0.4, label = "Student marks");
# Setting the x-acis label and its size
plt.xlabel("Students", size=15)
# Setting the y-axis label and its size
plt.ylabel("Marks Secured", size=15);
# Setting the title for the graph
plt.title("This is an annotated barplot")
for p in axes.patches:
axes.annotate(text=np.round(p.get_height(), decimals=2),
xy=(p.get_x()+p.get_width()/2., p.get_height()),
ha='center',
va='center',
xytext=(0, 10),
textcoords='offset points');
plt.legend(loc='best');
plt.show();
That produces:
Regards, Atapalou

How to update colours on bars after initial plotting

I have a bar chart, named 'b', plotted with a set of colors called color1. On a click event, I want the colours on the bar chart to be updated with a new set of colours called color2. I found that I have to enumerate through the BarContainer in order to change the colour. I was unable to just use b.set_color[color2]. Appreciate if anyone can tell me why is that so. Also, is there a pythonic way to do this besides to enumerate? Cheers.
This is the code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.random(size=4),
index=[1992,1993,1994,1995])
color1 = ['black', 'darkgrey', 'blue', 'lightsteelblue']
color2 = ['darkred', 'red', 'salmon', 'lightsalmon']
fig = plt.figure()
ax = plt.gca()
b = plt.bar(df.index.astype(str), df[0], width = 0.5, color=color1)
def onclick(event):
# method 1 works
for index, bar in enumerate(b):
bar.set_color(color2[index])
# method 2 doesn't work
b.set_color(color2)
fig.canvas.draw_idle()
plt.gcf().canvas.mpl_connect('button_press_event', onclick)
plt.show()

Edit line colors in a matplotlib Axis object

I generated a plot with 7 curves and saved it as a Matplotlib Axis object. However, now I want to change the colors in each one of those curves. Since the curves take a while to generate, is it possible to change the colors of these curves from the Axis object itself?
import matplotlib.pyplot as plt
import pickle
import numpy as np
fig, ax = plt.subplots()
x = np.arange(10)
y1 = np.random.random(10)
y2 = np.random.random(10)
kwargs_1 = {
'color': 'red',
'linestyle': ':',
'label': '1',
}
kwargs_2 = {
'color': 'blue',
'linestyle': '--',
'label': '2',
}
ax.plot(x, y1, **kwargs_1)
ax.plot(x, y2, **kwargs_2)
pickle.dump(ax, open('axis_obj.pkl', 'wb'))
plt.clf()
plt.close()
ax_read = pickle.load(open('axis_obj.pkl', 'rb'))
fig = plt.figure()
ax_read.figure = fig
fig.axes.append(ax_read)
fig.add_axes(ax_read)
# and now I'm stuck on how to access the plot kwargs used earlier for this ax_read object
ax.get_lines() is a better way.
You can change the colors by using this code:
# change the color of the plot lines:
ax.properties()['children'][0].set_color('green')
ax.properties()['children'][1].set_color('black')
Explanation: The axes object has the attribute properties which holds the children of the axes object. children is a list containing all objects which were drawn to the axis:
>>> ax.properties()['children']
[
<matplotlib.lines.Line2D at 0x7f2edb896b70>,
<matplotlib.lines.Line2D at 0x7f2edb896ac8>,
...]
The first two elements are the plots which you have drawn to the axis.

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.

seaborn or matplotlib line chart, line color depending on variable

I have a pandas dataframe with three columns, Date(timestamp), Color('red' or 'blue') and Value(int).
I am currently getting a line chart from it with the following code:
import matplotlib.pyplot as plt
import pandas as pd
Dates=['01/01/2014','02/01/2014','03/01/2014','04/01/2014','05/01/2014','06/01/2014','07/01/2014']
Values=[3,4,6,5,4,5,4]
Colors=['red','red','blue','blue','blue','red','red']
df=pd.DataFrame({'Dates':Dates,'Values':Values,'Colors':Colors})
df['Dates']=pd.to_datetime(df['Dates'],dayfirst=True)
grouped = df.groupby('Colors')
fig, ax = plt.subplots()
for key, group in grouped:
group.plot(ax=ax, x="Dates", y="Values", label=key, color=key)
plt.show()
I'd like the line color to depend on the 'color' columns. How can I achieve that?
I have seen here a similar question for scatterplots, but it doesn't seem I can apply the same solution to a time series line chart.
My output is currently this:
I am trying to achieve something like this (one line only, but several colors)
As I said you could find the answer from the link I attached in the comment:
Dates = ['01/01/2014', '02/01/2014', '03/01/2014', '03/01/2014', '04/01/2014', '05/01/2014']
Values = [3, 4, 6, 6, 5, 4]
Colors = ['red', 'red', 'red', 'blue', 'blue', 'blue']
df = pd.DataFrame({'Dates': Dates, 'Values': Values, 'Colors': Colors})
df['Dates'] = pd.to_datetime(df['Dates'], dayfirst=True)
grouped = df.groupby('Colors')
fig, ax = plt.subplots(1)
for key, group in grouped:
group.plot(ax=ax, x="Dates", y="Values", label=key, color=key)
When color changing you need to add extra point to make line continuous