python matplotlib markerscale for area plot [duplicate] - python

This question already has answers here:
increase the linewidth of the legend lines in matplotlib
(4 answers)
Closed 5 years ago.
What I want to do is a plot of generation and demand in an electricity grid with Matplotlib in Python. This is my code:
fig,ax = plt.subplots(figsize=(14,8))
generation.plot(kind="area", ax=ax, linewidth=1, alpha=0.9)
load.plot(kind="area", ax=ax, linewidth=1, alpha=0.9)
labels = ['Erzeugung', 'Last']
ax.legend(labels, ncol=4, loc="best", markerscale=10)
ax.set_ylabel("GW")
ax.set_xlabel("")
plt.tight_layout()
The result looks like this:
My question is about the markerscale: Why doesn't it work with this kind of plot? The problem is the bad visibility of the marker in the legend, it would be much better with a thicker line or even a box. And this without increasing the line width of the lines. Any ideas?

You can set the line size manually after creation as follows:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
fig, ax = plt.subplots(figsize=(14,8))
generation = pd.DataFrame(np.random.randint(10, 14, 10))
load = pd.DataFrame(np.random.randint(2, 5, 10))
generation.plot(kind="area", ax=ax, linewidth=1, alpha=0.9)
load.plot(kind="area", ax=ax, linewidth=1, alpha=0.9)
labels = ['Erzeugung', 'Last']
legend = ax.legend(labels, ncol=4, loc="best")
for handle in legend.legendHandles:
handle.set_linewidth(3.0)
ax.set_ylabel("GW")
ax.set_xlabel("")
plt.tight_layout()
plt.show()
Giving you something like:

Related

Add legend to chart with data from different columns [duplicate]

This question already has answers here:
Add Legend to Seaborn point plot
(4 answers)
Closed 7 months ago.
How do I add a legend to a chart where I am showing data from more than one column? The legend isn't appearing automatically and if I use ax.legend() then I get an error message like this: [WARNING] No artists with labels found to put in legend.
This is what the code looks like:
fig, ax = plt.subplots()
sns.lineplot(x=data.index, y=data[('s', 'a')], color='black', marker='o')
sns.lineplot(x=data.index, y=data[('s', 'f')], color='firebrick', linewidth=1, linestyle='--')
ax.fill_between(x=data.index, y1=data[('s', 'l')], y2=data[('s', 'u')], color='firebrick', alpha=0.2)
ax.legend()
This is what data looks like (using dummy data):
pd.DataFrame(data=[[1,1.1,0.7,1.3],[2,1.9,1.7,2.3],[3,2.8,2.7,3.3]], index=['2022-01-01', '2022-02-01', '2022-03-01'], columns=pd.MultiIndex.from_tuples([('s','a'),('s','f'),('s','l'),('s','u')]))
Not sure what I'm doing wrong but I'd like a legend that shows what the black line, red dotted line and range are.
Add label to your plots like so:
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
data = pd.DataFrame(data=[[1,1.1,0.7,1.3],[2,1.9,1.7,2.3],[3,2.8,2.7,3.3]], index=['2022-01-01', '2022-02-01', '2022-03-01'], columns=pd.MultiIndex.from_tuples([('s','a'),('s','f'),('s','l'),('s','u')]))
fig, ax = plt.subplots()
sns.lineplot(x=data.index, y=data[('s', 'a')], color='black', marker='o', label = "s a")
sns.lineplot(x=data.index, y=data[('s', 'f')], color='firebrick', linewidth=1, linestyle='--', label="s f")
ax.fill_between(x=data.index, y1=data[('s', 'l')], y2=data[('s', 'u')], color='firebrick', alpha=0.2, label="range")
ax.legend()
Output:

Why can't I remove pyplot tick labels? [duplicate]

This question already has answers here:
How to disable the minor ticks of log-plot in Matplotlib?
(3 answers)
Closed 2 years ago.
Why doesn't ax1.set_yticks([]), plt.yticks([]), plt.setp(ax1.get_yticklabels(),visible=False)
plt.gca().set_yticks([]), nor
plt.tick_params(left=False,bottom=False,labelleft=False,abelbottom=False) remove the tick numbers in this plot?
import numpy as np
import matplotlib.pyplot as plt
xscalespace=np.logspace(1, 6, num=6)
fig, (ax1, ax2) = plt.subplots(2, sharey=False, figsize=(5,5))
frequenz = np.exp(np.linspace(0,1,11)*20)#dummy lines doesn't matter
amplitude = np.exp(-np.linspace(0,1,11))#they don't matter
plt.sca(ax1)
plt.xscale('log')
plt.yscale('log')
ax1.plot(frequenz,amplitude/15,"*",label="plot",color="green")
plt.legend()
plt.grid()
plt.ylim(0.1, 1)
ax1.set_yticks([])
plt.yticks([])
plt.setp(ax1.get_yticklabels(),visible=False)
plt.gca().set_yticks([])
plt.tick_params(left=False,
bottom=False,
labelleft=False,
labelbottom=False)
The reason I ask is, I am setting my own labels but they create conflict with these irremovable labels. And I've tried everything, but nothing seems to work.
You can try specifying xticks and xticklabels from the setp function to force label deletions
plt.setp(ax1, xticks=[1,2,3,4,5],
xticklabels=['','','','',''],
yticks=[1,2,3,4,5],
yticklabels=["",'','',''])

Increase font-size of labels in Pie chart matplotlib [duplicate]

This question already has answers here:
How to change the font size on a matplotlib plot
(16 answers)
Closed 3 years ago.
I have a pie chart that looks like:
I tried increasing the font size using textprops={'fontsize': 18}). However, it only changes the font-size of the percentage labels inside pie, and the labels outside remain un-affected.
I want to increase fontsize of labels A, B,C etc in above pie chart.
My code:
fig1, ax1 = plt.subplots(figsize=(24,12))
flavor_pie = ax1.pie(data2.Count_Of_labels,labels=['A','B','C','D','E','F'], autopct='%.0f%%', shadow=True, colors=colors,
explode= explode1, startangle= -90, textprops={'fontsize': 18})
centre_circle = plt.Circle((0,0),0.20,fc='white')
fig = plt.gcf()
fig.gca().add_artist(centre_circle)
ax1.axis('equal')
plt.tight_layout()
plt.show()
Try:
import matplotlib as mpl
mpl.rcParams['font.size'] = 18.0
or,
mpl.rcParams.update({'font.size': 18})
or,
import matplotlib.pyplot as plt
plt.rcParams['font.size'] = 18
You might be using an older version of matplotlib; in any newer version both, the labels and autopercentages have the same size.
The question would hence boil down to how to set different font sizes for labels and autopercentages.
Having a pie chart like this
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
wedges, labels, autopct = ax.pie([1,2,3,4,3,2],labels=['A','B','C','D','E','F'],
autopct='%.0f%%', wedgeprops=dict(width=.7))
you can loop over the labels or autopercentages and set the fontsize like
for lab in labels:
lab.set_fontsize(15)
or set them all at once, like
plt.setp(labels, fontsize=15)
And similar for autopct.

Creating sparklines using matplotlib in python

I am working on matplotlib and created some graphs like bar chart, bubble chart and others.
Can some one please explain with an example what is difference between line graph and sparkline graph and how to draw spark line graphs in python using matplotlib ?
for example with the following code
import matplotlib.pyplot as plt
import numpy as np
x=[1,2,3,4,5]
y=[5,7,2,6,2]
plt.plot(x, y)
plt.show()
the line graph generated is the following:
But I couldn't get what is the difference between a line chart and a spark lien chart for the same data. Please help me understand
A sparkline is the same as a line plot but without axes or coordinates. They can be used to show the "shape" of the data in a compact way.
You can cram several line plots in the same figure just by using subplots and changing properties of the resulting Axes for each subplot:
data = np.cumsum(np.random.rand(1000)-0.5)
data = data - np.mean(data)
fig = plt.figure()
ax1 = fig.add_subplot(411) # nrows, ncols, plot_number, top sparkline
ax1.plot(data, 'b-')
ax1.axhline(c='grey', alpha=0.5)
ax2 = fig.add_subplot(412, sharex=ax1)
ax2.plot(data, 'g-')
ax2.axhline(c='grey', alpha=0.5)
ax3 = fig.add_subplot(413, sharex=ax1)
ax3.plot(data, 'y-')
ax3.axhline(c='grey', alpha=0.5)
ax4 = fig.add_subplot(414, sharex=ax1) # bottom sparkline
ax4.plot(data, 'r-')
ax4.axhline(c='grey', alpha=0.5)
for axes in [ax1, ax2, ax3, ax4]: # remove all borders
plt.setp(axes.get_xticklabels(), visible=False)
plt.setp(axes.get_yticklabels(), visible=False)
plt.setp(axes.get_xticklines(), visible=False)
plt.setp(axes.get_yticklines(), visible=False)
plt.setp(axes.spines.values(), visible=False)
# bottom sparkline
plt.setp(ax4.get_xticklabels(), visible=True)
plt.setp(ax4.get_xticklines(), visible=True)
ax4.xaxis.tick_bottom() # but onlyt the lower x ticks not x ticks at the top
plt.tight_layout()
plt.show()
A sparkline graph is just a regular plot with all the axis removed. quite simple to do with matplotlib:
import matplotlib.pyplot as plt
import numpy as np
# create some random data
x = np.cumsum(np.random.rand(1000)-0.5)
# plot it
fig, ax = plt.subplots(1,1,figsize=(10,3))
plt.plot(x, color='k')
plt.plot(len(x)-1, x[-1], color='r', marker='o')
# remove all the axes
for k,v in ax.spines.items():
v.set_visible(False)
ax.set_xticks([])
ax.set_yticks([])
#show it
plt.show()

Why I get additional empty plot in matplotlib?

I have the following code in my IPython notebook:
import matplotlib.pyplot as plt
plt.setp(plt.xticks()[1], rotation=45)
plt.figure(figsize=(17, 10)) # <--- This is the problematic line!!!!!!!!!!!!!
plt.plot_date(df['date'],df['x'], color='black', linestyle='-')
plt.plot_date(df['date'],df['y'], color='red', linestyle='-')
plt.plot_date(df['date'],df['z'], color='green', linestyle='-')
In the above example df is pandas data frame.
Without the marked line (containig figsize) the plot is too small. With the mentioned line I have an increased image as I want but before it I have an additional empty plot.
Does anybody know why it happens an how this problem can be resolved?
Try reversing the first two lines after the import. plt.setp is opening a figure.
here's how I would do this:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(17, 10))
plt.setp(plt.xticks()[1], rotation=45)
ax.plot_date(df['date'],df['x'], color='black', linestyle='-')
ax.plot_date(df['date'],df['y'], color='red', linestyle='-')
ax.plot_date(df['date'],df['z'], color='green', linestyle='-')
It's a good practice to explicitly create and operate on your your Figure and Axes objects.

Categories

Resources