This question already has answers here:
secondary_y=True changes x axis in pandas
(2 answers)
Plot multiple Y axes
(3 answers)
Closed 4 years ago.
I want to add secondary y-axis. I have my data in CSV with three column date, lscc and cc. I want to add LSCC as first y-axis and CC as secondry. so far I have done this
df=pd.read_csv("E29Lsccvalue.csv", index_col='Date' )
plt.ylabel("")
plt.xlabel("Low level Similarity Class Cohesion (LSCC) Evolution")
df.plot(kind="line", marker='o',legend=None)
plt.xticks(rotation=90)
plt.show()
thanks
Within matplotlib I have used twinx() when I want to utilize the existing X-axis I have created, yet plot more data on top with a different Y axis. In your case with df as the first plot object:
axCC = df.twinx() # second axis sharing the same X axis of the original
Then you can include plots, labels, and other parameters referenced to this axis through calls such as:
axCC.set_ylabel("ExampleLabel",color="tab:red")
axCC.plot(xData,yData,color="blue")
Etc, etc.
A fully functional example with more detail is shown here
Although no reproducible date is provided, I guess you can achieve the desired result by doing this:
ax = df.plot(secondary_y='CC')
eventually adding all your ax customization required
edit: dotted line customization
Suppose you need a dotted vertical line at a certain position on your x-axis (in this example, at position 2 from your pandas index), use axvline and ':' as linestyle (dots)
ax = a.plot(secondary_y='Price')
ax.axvline(a.index.values[2], linestyle=':')
Related
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
This question already has answers here:
Improve subplot size/spacing with many subplots
(8 answers)
Closed 1 year ago.
Hi I'm very new to Python, and I'm trying to fix the labels because they overlap, (as seen in the picture). I figured the hspace and the wspace is the columns, but I'm not sure exactly how to adjust everything else in the labels, I don't want to mess with the x axis. Is there a way to make this plot look clearer?
Here's what I have:
_, axes = plt.subplots(nrows=6, ncols=6, sharex=True)
plt.suptitle('mean activity duration by time of day')
plt.subplots_adjust(hspace=0.5, wspace=0.5)
for ax, (activity, df) in zip(axes.ravel(), df_all.groupby('e')):
(df.groupby('f')
.d
.mean()
.plot(ax=ax,
kind='bar',
title=activity,
xlabel='time'))
6 x 6 bar graph:
Use constrained_layout.
use a larger figure size so your titles are not larger than your axes
use a smaller font size for the titles.
You can use tight_layout if you prefer, but constrained_layout is more flexible.
You can try to use plt.tight_layout, adjusts subplot params so that the subplot(s) fits in to the figure area
I'm trying to plot a line chart based on 2 columns using seaborn from a dataframe imported as a .csv with pandas.
The data consists of ~97000 records across 19 years of timeframe.
First part of the code: (I assume the code directly below shouldn't contribute to the issue, but will list it just in case)
# use pandas to read CSV files and prepare the timestamp column for recognition
temporal_fires = pd.read_csv("D:/GIS/undergraduateThesis/data/fires_csv/mongolia/modis_2001-2019_Mongolia.csv")
temporal_fires = temporal_fires.rename(columns={"acq_date": "datetime"})
# recognize the datetime column from the data
temporal_fires["datetime"] = pd.to_datetime(temporal_fires["datetime"])
# add a year column to the dataframe
temporal_fires["year"] = temporal_fires["datetime"].dt.year
temporal_fires['count'] = temporal_fires['year'].map(temporal_fires['year'].value_counts())
The plotting part of the code:
# plotting (seaborn)
plot1 = sns.lineplot(x="year",
y="count",
data=temporal_fires,
color='firebrick')
plt.gca().xaxis.set_major_formatter(FuncFormatter(lambda x, _: int(x)))
plt.xlabel("Шаталт бүртгэгдсэн он", fontsize=10)
plt.ylabel("Бүртгэгдсэн шаталтын тоо")
plt.title("2001-2019 он тус бүрт бүртгэгдсэн шаталтын график")
plt.xticks(fontsize=7.5, rotation=45)
plt.yticks(fontsize=7.5)
Python doesn't return any errors and does show the figure:
... but (1) the labels are not properly aligned with the graph vertices and (2) I want the X label ticks to show each year instead of skipping some. For the latter, I did find a stackoverflow post, but it was for a heatmap, so I'm not sure how I'll advance in this case.
How do I align them properly and show all ticks?
Thank you.
I found my answer, just in case anyone makes the same mistake.
The line
plt.gca().xaxis.set_major_formatter(FuncFormatter(lambda x, _: int(x)))
converted the X ticks on my plot to to its nearest number, but the original values stayed the same. The misalignment was because I had just renamed the "years" "2001.5" to "2001", not actually modifying the core data itself.
As for the label intervals, the addition of this line...
plt.xticks(np.arange(min(temporal_fires['year']), max(temporal_fires['year'])+1, 1.0))
...showed me all of the year values in the plot instead of skipping them.
This question already has answers here:
Creating figure with exact size and no padding (and legend outside the axes)
(2 answers)
How to put the legend outside the plot
(18 answers)
Closed 4 years ago.
I am trying to put a legend below a graph but keeping the figure size fixed.
Is this possible?
I saw How to put the legend out of matplotlib plot and https://stackoverflow.com/a/4701285/7746941 but the first one does not address fitting the legend within a predefined figure size while the second one does not do this generically (there is an example where the axes width is shrunk by 0.8 to accommodate the legend) .
Below is my current solution that anchors the legend at the bottom of the graph but the legend does not fit the figure.
I cannot figure out how to determine the height of the legend box to move the axis up by that amount.
import pandas as pd
df = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6]})
ax = df.plot(figsize=(4,4))
tight_box = ax.transAxes.inverted().transform(ax.get_tightbbox(ax.figure.canvas.get_renderer()))
leg = ax.legend(bbox_to_anchor=(0,tight_box[0][1],1,0), loc='upper center')
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.