I'm using matplotlib.pyplot for plot a scatterplot. The following code produces a scatterplot that does not match this request.
months = []
data = [...] #some data in list form
#skipping the 8th value since I don't want data to refer at this value
for i in [x for x in range(1, len(data) +2) if x != 8]:
months.append(i)
fig, ax = plt.subplots()
plt.scatter(months,data)
plt.scatter([months[-1]],[data[-1]], color=['red'])
plt.title('Quantity scatterplot')
ax.set_xlabel('Months')
ax.set_ylabel('Quantities')
ax.legend(['Historical quantities','Forecasted quantity'], loc=1)
plt.show()
While I would like to see all months (from 1 to 10) on x-axis
The easiest way to force all numbers between 1 and 10 to appear as ticklabels on the x axis is to use
ax.set_xticks(range(1,11))
For the more general case where axis limits are not determined beforehands you may get ticklabels at integer positions using a matplotlib.ticker.MultipleLocator.
ax.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(1))
where 1 is the number of which all ticks should be multiples of.
Related
This might be a very simple question, but I just could not get the trick for this problem .
I want to plot multiple subplots, but when I have done that and use my defined axis limits, I find there is overlapping of axis. Y axis should be same in each column. Any tips to remove this:
My simplified script is here:
column = 2
num=len(sta_files)
fig, axes = plt.subplots(nrows=num, ncols=column,figsize=(15,15))
n=0
for event_file in sta_files:
axes[n,0].plot(np.arange(0,len(st[0].data))*1/sampling_rate,
st[0].data+i,color='k',linewidth=0.7)
axes[n,0].set_xlim((0, 35))
spl2 = st[0]
fig = spl2.spectrogram(show=False, axes=axes[n,1])
mappable = axes[n,1].images[0]
Here is my output:
I have the following code that builds the empirical function according to data stored in Z_score_list.
Z_score_list.sort()
edf = []
step = 1 / len(Z_score_list)
for i in range(len(Z_score_list)):
edf.append(step * i)
edf = np.array(edf)
fig, ax = plt.subplots()
ax.plot(Z_score_list, edf,
'b--', lw=3, alpha=0.6, label='Эмпирическая')
plt.show()
As a result I have this:
There isn't enough space for X axis. So it breaks the plot and continues it from the start of X axis to its end. How can I scale this graphic for the one continuous line that will be independent from Z_score_list size?
The problem wasn't in plot function itself, there were NaN values in Z_score_list and every occurance of it starts sort again from the index NaN was occured. Removing these values made it all ok.
I want to arrange the values of y-axis in seaborn graph.
I want to increase number in such kind of order -> 100,1000,10000
How can I do that.
I can use this seaborn graph code defined below.
ax = sns.lineplot
You can use ax.set_yticks and pass a list of ticker values you want to set on y axis (and ax.set_xticks for x axis)
ax = sns.lineplot(x, y);
ax.set_yticks([100,1000,10000])
And of course you can generate your list using list comprehension
yticks = [10**i for i in range(2, 5)]
ax.set_yticks(yticks)
Alternately, you can also use ax.set_ylim which takes a start and end value.
ax.set_ylim(100, 1000), but I don't think you can specify the increment in this function.
I wish to clarify two queries in this post.
I have a pandas df like below picture.
1. Plotting problem : .
When i try to plot column 0 with column 1, the values gets sorted.
example : in col_0 I have values starting from 112 till 0.
the values gets sorted in ascending order and the graph shows reversed X axis plot when i use the below code.
plt.plot(df.col_0, df.col_1)
What will be best way to avoid sorting X axis values. ?
2. All paramaters in single graph
I would like to plot all the params in a single plot. Except X axis all other params values are between 0 to 1 (same scale)
What will be best pythonic way of doing.
Any help would be appreciated.
Try to draw the series/dataframe against the index:
col_to_draw = [col for col in df.columns if col!='col0']
# if your data frame is indexed as 0,1,2,... ignore this step
tmp_df = df.reset_index()
ax = tmp_df[col_to_draw].plot(figsize=(10,6))
xtick_vals = ax.get_xticks()
ax.set_xticklabels(tmp_df.col0[xtick_vals].tolist())
Output:
I don't understand what you mean by they get sorted - does it not plot 112, 0.90178 and connect it to 110.89899, 0.90779, etc?
To share the X axis but have 2 Y axes that certain sets are plotted on, use twinx
fig, ax1 = plt.subplots()
ax1.plot(df.col_0, df.col_1)
ax2 = ax1.twinx()
ax2.plot(df.col_0, df.col_2)
re: how to plot in the order you want
I believe your intention is to actually plot these values vs. time or index. To that end, I suggest:
fig, ax1 = plt.subplots()
ax1.plot(df['Time'], df.col_0) # or df.index, df.col_0
ax2 = ax1.twinx()
ax2.plot(df['Time'], df.col_1)
I plotting a pandas dataframe to a seaborn heatmap, and I would like to set specific y-axis ticks for specific locations.
My dataframe index is 100 rows which corresponds to a "depth" parameter, but the values in this index are not arranged with a nice interval :
I would like to set tick labels at multiples of 100. I can do this fine using :
yticks = np.linspace(10,100,10)
ylabels = np.linspace(100,1000,10)
for my dataframe which has 100 rows, with values from approx 100 - 1000, but the result is clearly not desirable, as the position of the tick labels clearly do not correspond to the correct depth values (index value), only the position in the index.
How can I produce a heatmap where the plot is warped so that the actual depth values (index values) are aligned with the ylabels I am setting?
A complicating factor for this is also that the index values are not sampled linearly...
My solution is a little bit ugly but it works for me. Suppose your depth data is in depth_list and num_ticks is the number of ticks you want:
num_ticks = 10
# the index of the position of yticks
yticks = np.linspace(0, len(depth_list) - 1, num_ticks, dtype=np.int)
# the content of labels of these yticks
yticklabels = [depth_list[idx] for idx in yticks]
then plot the heatmap in this way (where your data is in data):
ax = sns.heatmap(data, yticklabels=yticklabels)
ax.set_yticks(yticks)
plt.show()
While plotting with seaborn you have to specify arguments xticklabels and yticklabels for heatmap function. These arguments in you case have to be lists with custom tick labels.
I have developed a solution which does what I intended, modified after liwt31's solution:
def round(n, k):
# function to round number 'n' up/down to nearest 'k'
# use positive k to round up
# use negative k to round down
return n - n % k
# note: the df.index is a series of elevation values
tick_step = 25
tick_min = int(round(data.index.min(), (-1 * tick_step))) # round down
tick_max = (int(round(data.index.max(), (1 * tick_step)))) + tick_step # round up
# the depth values for the tick labels
# I want my y tick labels to refer to these elevations,
# but with min and max values being a multiple of 25.
yticklabels = range(tick_min, tick_max, tick_step)
# the index position of the tick labels
yticks = []
for label in yticklabels:
idx_pos = df.index.get_loc(label)
yticks.append(idx_pos)
cmap = sns.color_palette("coolwarm", 128)
plt.figure(figsize=(30, 10))
ax1 = sns.heatmap(df, annot=False, cmap=cmap, yticklabels=yticklabels)
ax1.set_yticks(yticks)
plt.show()