I need to create a graph with uneven 'x axis' and label them.
For example:
x = [2,5,10,20,30]
y = [100,200,312,788,123]
I want the x axis on plot to be spaced as x itself. I solved the issue with following code. But instead of exact x values I would like to name them in the order of occurrence, ie 1,2,3,4,5 in place of 2,5,10,20,30.
Thank you
plt.figure(30)
plt.plot(x,y,color='b',alpha=1)
plt.title('R_variation',fontsize=20)
plt.ylabel(r'R',fontsize=20,color='k')
plt.xlabel('Time (hr)',fontsize=20,color='k')
plt.xticks(x, rotation='vertical')
plt.grid()
plt.show()
Related
I have two csv files that have been generated on one chronological basis during my recording (they both have a timestamp column based on one clock).
I want to plot my data in matplotlib (or elsewhere using python, if you have a better suggestion).
On my primary x axis, I want to have the general continuous timestamps (from csv file 1).
On my y axis I need the recordings of my desired variable (from csv file 1).
On my secondary x axis, I need to have my experiment events or annotations (from csv file 2), right at the timestamps (ticks) when they happened.
I try to plot all of these, this way:
ticks = annotations_pd_frame['timestamp']
labels = annotations_pd_frame['label']
fig, ax1 = plt.subplots()
ax2 = ax1.twiny()
fig.set_figheight(5)
fig.set_figwidth(25)
ax1.yaxis.grid()
plt.xticks(ticks, labels)
plt.plot(pupil_data_in_trial_eye0['pupil_timestamp'].loc[pupil_data_in_trial_eye0['trial'] == trial_label], pupil_data_in_trial_eye0['diameter_3d'].loc[pupil_data_in_trial_eye0['trial'] == trial_label])
plt.plot(pupil_data_in_trial_eye1['pupil_timestamp'].loc[pupil_data_in_trial_eye1['trial'] == trial_label], pupil_data_in_trial_eye1['diameter_3d'].loc[pupil_data_in_trial_eye1['trial'] == trial_label])
plt.legend(['eye0', 'eye1'])
ax1.set_xlabel('Timestamps [s]')
ax1.set_ylabel('Diameter [mm]')
plt.title('Pupil Diameter in ' + str(label) )
plt.grid(b=True)
An example of the csv files is here :
https://gist.github.com/Zahra-on-Github/aa67a3e309fa66582a118f5c08509f77
First figure is when I plot my main data using plt.plot
and I get correct ticks and labels (ticks and labels correctly shown as they happened in this one trial of data),
but incorrect timestamps on the primary x axis.
Second figure is when I plot my main data using ax1.plot
and I get correct timestamps on primary x axis,
but incorrect ticks and labels (the whole run’s ticks and labels are shown for this one trial of data).
Any ideas what I'm doing wrong?
I solved it like this:
for (t, l) in zip(ticks, labels):
ax1.axvline(t, color='black', linestyle='--')
trans = mtransforms.blended_transform_factory(ax1.transData, ax1.transAxes)
ax1.text(t, 1.1, l, ha='center', transform=trans, rotation = 30)
I have created a figure that has two y axes that are sharing one x axis. The y axes are correlated to each other: the values of the left y-axis are an input to an equation that gives the values of the right y-axis. To correlate the two, I set the y ticks on each axis to be the same. Then I tried to use a function (myticks) to label the y ticks on each axis with the proper labels using set_major_formatter(ticker.FuncFormatter(myticks)). The y ticks are in the correct position on each axes and the labels are correct on the left axis, but the labels are incorrect on the right axis. For some reason, the left axis labels are showing up on the right axis as well. The values of the right axis should be the values present in right_y2. I'm brand new to Python, so any help is greatly appreciated!
#plot
fig = plt.figure(figsize=(3,4))
ax1 = fig.add_subplot(111)
y =[1.9E19,1E20,5E20,1.8E21,1E22,1.9E22,1.15E23]
ax1.plot(2,y[0],marker='o')
ax1.plot(2,y[1],marker='o')
ax1.plot(2,y[2],marker='o')
ax1.plot(2,y[3],marker='o')
ax1.plot(2,y[4],marker='o')
ax1.plot(2,y[5],marker='o')
ax1.plot(2,y[6],marker='o')
ax1.set_yscale("log")
ax1.set_ylim(1E19,2E23)
ax1.set_yticks(y)
def myticks(left_y,y):
exponent = int(np.log10(left_y))
coeff = left_y/10**exponent
return r"${:2.0f} \times 10^{{ {:2d} }}$".format(coeff,exponent)
ax1.yaxis.set_major_formatter(ticker.FuncFormatter(myticks))
ax2 = ax1.twinx()
ax2.set_yscale("log")
ax2.set_ylim(1E19,2E23)
ax2.set_yticks(y)
def myticks2(right_y2,y):
exponent2 = int(np.log10(right_y2))
coeff2 = right_y2/10**exponent2
return r"${:2.0f} \times 10^{{ {:2d} }}$".format(coeff2,exponent2)
ax2.yaxis.set_major_formatter(ticker.FuncFormatter(myticks2)
where
left_y =[1.9E19,1E20,5E20,1.8E21,1E22,1.9E22,1.15E23]
right_y2 =[5.3E12,3.8E13,1.3E14,2.7E14,5E14,9.6E14,3E15]
I get the following figure:
enter image description here
I am trying to have my graph show the x labels in the order of the below. But its putting them in the graph based on their values.
Can someone advise how to force the plot to show them in the below order?
How I want the X-axis to be ordered:
'TD1BALMO','TD1CURMON','TD1+1_M', 'TD1+2_M', 'TD1+3_M', 'TD1+4_M', 'TD1+5_M'
how it is being ordered (I don't know why)
'TD1+1_M', 'TD1+2_M', 'TD1+3_M', 'TD1+4_M', 'TD1+5_M', 'TD1BALMO','TD1CURMON'
Assign routes for 3.30.2020 to a variable:
TD3_FFA_Months = FFA_dirty_rates[FFA_dirty_rates.RouteIdentifier.isin(['TD1BALMO','TD1CURMON','TD1+1_M', 'TD1+2_M', 'TD1+3_M', 'TD1+4_M', 'TD1+5_M']) & (FFA_dirty_rates.ArchiveDate == '2020-03-30')]
Visualizing the data
fig = plt.figure(figsize=(10, 8))
plt.plot('RouteIdentifier', 'RouteAverage', data=TD3_FFA_Months, marker='o', markerfacecolor='blue', markersize=12, color='skyblue', linewidth=4)
plt.xlabel('Forward Months')
plt.ylabel('WS Rates')
plt.title('Rates over months and years')
plt.show()
I am having trouble putting in a picture but the chart is showing the X axis in the below order. Notice the TD1BALMO and TD1CURMO were placed at the end of the x axis.
'TD1+1_M', 'TD1+2_M', 'TD1+3_M', 'TD1+4_M', 'TD1+5_M', 'TD1BALMO','TD1CURMON'
I'm making a histogram in matplotlib and the text label for each bin are overlapping on each other like this:
I tried to rotate the labels on the x-axis by following another solution
cuisine_hist = plt.hist(train.cuisine, bins=100)
cuisine_hist.set_xticklabels(rotation=45)
plt.show()
But I get error message 'tuple' object has no attribute 'set_xticklabels'. Why? How do I solve this problem? Alternatively, how can I "transpose" the plot so the labels are on the vertical axis?
Here you go. I lumped both answers in one example:
# create figure and ax objects, it is a good practice to always start with this
fig, ax = plt.subplots()
# then plot histogram using axis
# note that you can change orientation using keyword
ax.hist(np.random.rand(100), bins=10, orientation="horizontal")
# get_xticklabels() actually gets you an iterable, so you need to rotate each label
for tick in ax.get_xticklabels():
tick.set_rotation(45)
It produces the graph with rotated x-ticks and horizontal histogram.
The return value of plt.hist is not what you use to run the function set_xticklabels:
What's running that function is a matplotlib.axes._subplots.AxesSubplot, which you can get from here:
fig, ax = plt.subplots(1, 1)
cuisine_hist = ax.hist(train.cuisine, bins=100)
ax.set_xticklabels(rotation=45)
plt.show()
From the "help" of plt.hist:
Returns
-------
n : array or list of arrays
The values of the histogram bins. See *normed* or *density*
bins : array
The edges of the bins. ...
patches : list or list of lists
...
This might be helpful since it is about rotating labels.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [1, 4, 9, 6]
labels = ['Frogs', 'Hogs', 'Bogs', 'Slogs']
plt.plot(x, y, 'ro')
# You can specify a rotation for the tick labels in degrees or with keywords.
plt.xticks(x, labels, rotation='vertical')
# Pad margins so that markers don't get clipped by the axes
plt.margins(0.2)
# Tweak spacing to prevent clipping of tick-labels
plt.subplots_adjust(bottom=0.15)
plt.show()
so I think
plt.xticks(x, labels, rotation='vertical')
is the important line right here.
just this simple line would do the trick
plt.xticks(rotation=45)
I am plotting 2 lines and a dot, X axis is a date range. The dot is most important, but it appears on the boundary of the plot. I want to "expand" the plot further right so that the dot position is more visible.
In other words I want to expand the X axis without adding new values to Y values of lines. However if I just add a few dates to X values of lines I get the "x and y dimensions must be equal" error. I tried to add a few np.NaN values to Y so that dimensions are equal, but then I get an error "integer required".
My plot:
My code:
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
plot_x = train_original.index.values
train_y = train_original.values
ax1.plot(plot_x, train_y, 'grey')
x = np.concatenate([np.array([train_original.index.values[-1]]), test_original.index.values])
y = np.concatenate([np.array([train_original.dropna().values[-1]]), test_original.dropna().values])
ax1.plot(x, y, color='grey')
ax1.plot(list(predicted.index.values), list(predicted.values), 'ro')
ax1.axvline(x=train_end, alpha=0.7, linestyle='--',color='blue')
plt.show()
There are a couple of ways to do this.
An easy, automatic way to do this, without needing knowledge of the existing xlim is to use ax.margins. This will add a certain fraction of the data limits to either side of the plot. For example:
ax.margins(x=0.1)
will add 10% of the current x range to both ends of the plot.
Another method is to explicitly set the x limits using ax.set_xlim.
Just change the xlim(). Something like:
xmin, xmax = plt.xlim() # return the current xlim
plt.xlim(xmax=xmax+1)