Undesired shadow in matplotlib pyplot [duplicate] - python

This question already has answers here:
Convert dataframe index to datetime
(4 answers)
Plot the x-axis as a date
(2 answers)
Plotting dates on the x-axis
(4 answers)
Closed 5 months ago.
I'm trying to plot some data for school project. However an ugly shadow appears when I do so. I have no clue of what it can be.
Here is my code:
index_labels = np.empty(len(smoothed), dtype=object)
for i in range(len(index_labels)):
index_labels[i] = ""
if i%365 == 0:
index_labels[i] = 2015 + int(i//365)
plt.scatter(smoothed.index, smoothed.national, label='PV load factor rolling mean over 24h.')
plt.plot(smoothed.index, sin_ref, color='red', label='Sinusoidal reference')
ax = plt.gca()
ax.set_xticklabels(index_labels)
# plt.legend()
plt.show()
and here is the different variables used so you have an idea:
and a zoom on the plot :
Thanks to all of you! Greetings :)

Solution from #BigBen:
from matplotlib.ticker import MultipleLocator
plt.scatter(smoothed.index, smoothed.national, label='PV load factor rolling mean over 24h.')
plt.plot(smoothed.index, sin_ref, color='red', label='Sinusoidal reference')
ax = plt.gca()
ax.xaxis.set_major_locator(MultipleLocator(730))
plt.show()
Multiple has a very good name: it only shows the label for the multiple of n.
EDIT: as find later, matplotlib do auto axis labeling for dates. Only problem was that column was recognized as string. pandas.to_datetime allow you to convert it back to pandas datetime type.

Related

How do I change the labels of the style variables in the legend of a seaborn plot? [duplicate]

This question already has answers here:
Remap values in pandas column with a dict, preserve NaNs
(11 answers)
How to edit a seaborn legend title and labels for figure-level functions
(2 answers)
Edit legend title and labels of Seaborn scatterplot and countplot
(3 answers)
Closed 2 days ago.
I am trying to change a specific part of the legend in my plot in seaborn.
I wrote the following code to display a plot in seaborn. The plot can be seen below.
ax = sns.lineplot(data = weekly_port_ret,
x='week',y='R',hue='high_leverage',style='gsector')
ax.set(title='Weekly Portfolio Returns - Daily Rebalancing',
xlabel='Week in 2020',
ylabel='Weekly Return'
)
plt.show()
I am just trying to change where it says "20.0" in the legend to "Industrial", and where it says "45.0" to "IT". Does anyone know how to do this?
My plot:
You can assign the gsector column to the values (Industrial and IT) and map it so that you can see the legend as you want... Updated code below.
I used some dummy data, but your code should work as well.
Refer assign and map for more info..
mysector = {20:'Industrial', 45:'IT'}
ax = sns.lineplot(data = weekly_port_ret.assign(gsector=weekly_port_ret['gsector'].map(mysector)),
x='week',y='R',hue='high_leverage',style='gsector')
ax.set(title='Weekly Portfolio Returns - Daily Rebalancing',
xlabel='Week in 2020',
ylabel='Weekly Return'
)
plt.show()
Plot

How to use the data from csv file to Matplotlib Bar Chart in jupyter [duplicate]

This question already has an answer here:
A convenient way to plot bar-plot in Python pandas
(1 answer)
Closed 10 months ago.
Could someone help me with how to create a bar graph in python using a CSV file? I want to plot a bar graph with the x-axis as ReleaseMonth and the y-axis with Rating, which I can interpret which month has the highest rating from the bar graph.
Below is my data head:
import seaborn as sns
ax = sns.barplot(x="ReleaseMonth", y="Rating", data=df)
plt.show()
x_release_month = df["ReleaseMonth"]
y_rating = df["Rating"]
# setting the size of the figure
fig = plt.figure(figsize=(10,5))
#bar plot
plt.bar(x_release_month, y_rating)
plt.show()

X axis for plt plot python is cluttered together [duplicate]

This question already has answers here:
Matplotlib showing x-tick labels overlapping
(3 answers)
Closed 11 months ago.
plt.figure(figsize=(4,4))
aapl_data.plot.line(x='Date',y='Adj Close',title='test')
plt.ylabel('Adj Close')plt.show()
How do i declutter the X axis. I tried using figsize in the code but it does not do anything
Better show the whole code. Since I'm not sure if you have such a string: ax = plt.axes()
ax.xaxis.set_major_locator(mdates.DayLocator(interval = 3))
Try to formate the date
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%b'))
There can be two solutions to this problem.
Increasing the width of the window. This can be achieved by:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(40,4))
fig.add_subplot(1,1,1).plot([1,2,3], [1,2,3])
plt.show()
Making the labels vertical rather than horizontal. This can be done by:
plt.xticks(range(10), rotation='vertical')

How to plot y-axis to the opposite side? [duplicate]

This question already has answers here:
matplotlib y-axis label on right side
(4 answers)
Closed 2 years ago.
I have this chart below:
I would want the y-axis for the lower subplot to be plotted to the opposite side since that would make more sense. Is there a method for this? The ax.invert_yaxis() simply inverts the labels.
Note: For the curious, I simply used .invert_xaxis() to plot inverted bars.
I guess, what you are looking for is
ax[1].yaxis.set_ticks_position("right")
ax[1].yaxis.set_label_position("right")
of an axis object.
So with #meTchaikovsky's MVE code, you'll get
import numpy as np
from matplotlib import pyplot as plt
x = np.linspace(1,10,10)
y0 = np.random.randint(0,30,size=10)
fig,ax = plt.subplots(nrows=2,ncols=1,figsize=(8,6))
ax[1].set_xlim(0,30)
ax[0].barh(x,y0,color='violet')
ax[0].set_ylabel("Y-Axis")
ax[1].set_xlim(30,0)
ax[1].barh(x,y0,color='deepskyblue')
ax[1].yaxis.set_ticks_position("right")
ax[1].yaxis.set_label_position("right")
ax[1].set_ylabel("Y-Axis")
plt.show()

Python - Plot values in different color [duplicate]

This question already has answers here:
How to plot one line in different colors
(5 answers)
Closed 6 years ago.
I am new to matplotlib and I need to plot on the same figure a large amount of data. My initial code is
data = np.genfromtxt('Data.csv', delimiter=',', skip_header=10,
skip_footer=10, names=['CSX', 'CSY'])
fig = plt.figure()
myPlot = fig.add_subplot(111)
myPlot.plot(data['CSX'], data['CSY'], color='r', label='the data')
leg = myPlot.legend()
plt.show()
The result is acceptable, I need though to have two different colors on these data, based on a third value. Could you point me to the correct direction? Thanks!
Filter your data into 2 or more sets based on some value/condition and just call plot for each set of data with different colour values.

Categories