I have dates for tick marks on my x-axis. How can I make them automatically not overlap?
There are a lot of S.O. questions and posts about setting the tick interval - but this won't work for me since the date range for my plot can vary from 1 week, up to 1 year.
When people have plots with highly variable ranges, what is the method to make the x-axis ticks automatically not overlap?
plt.plot(date_list, unique_list)
plt.ylabel('# Uniques per day')
You could rotate the xticks by 90 degrees (or any other value):
plt.xticks(rotation=90)
maybe you need to call tight_layout() if the ticks are then out of the frame
plt.tight_layout()
Don't have enough rep to comment, because I don't think the tip I am offering could solve this problem, but I had exactly the same issue.
My solution is to make the plot itself flatter, by
plt.figure(figsize = (20,6)).
My reasoning is as such, there are only so many pixels and if changing the date format and rotation as suggested by others is not an option, maybe stretch the plot a bit?
Related
I am trying to plot line charts for both nighttime and daytime to compare the differences in traffic volume in both time periods.
plt.subplot(2,1,1) #plot in grid chart to better compare differences
by_hour_business_night['traffic_volume'].plot.line()
plt.title('Business Nights Traffic Volume by Hours')
plt.ylabel('Traffic Volume')
plt.ylim(0,6500)
plt.show()
The chart for nighttime shows up alright, but the xtick labels are in [0,5,10,15,20,25], how can I change the labels to fit the hours? Something along the lines like: [0,1,2,3,4,5,6,19,20,21,22,23]
I have tried
x=[0,1,2,3,4,5,6,19,20,21,22,23]
plt.xticks(x)
But then I just got [0-6] on the left, and [19-23] on the right, both crammed on either side, leaving the middle of the xticks blank.
Or is there a better way to plot the chart? Since there will be a breaking point between 6 and 19 hours, is there a way to avoid this?
I am new to python and matplotlib, so forgive me if my wordings aren't precise enough.
xticks takes in two arguments: an array-like object of the placements and an array-like object of the labels. So you can do something like this:
plt.xticks(x, x)
This will set a label equal to the placement of the xtick. For more info you can read the docs for xtick here
I have a bar graph which has datetimes on the x-axis. How can I add gaps between x-ticks with respect to the timedelta between each neighbour ticks? The solution does not have to be a bargraph, I can use any kind of graph which satisfies my problem.
For these kind of problems you may set x axis as date field. This will fill in na dates and leave gaps accordingly which is helpful to analyze time series and things like monthly spending and it's quite easy to do. Following code snipper should help.
ax = plt.subplot(111)
ax.bar(x, y, width=10)
ax.xaxis_date()
plt.show()
I have a plot of values w/ errorbars with a categorical variable on the X-axis, made using the errorbar method. I have followed the instructions here to create a discontinuity in the X-axis (I'm only showing points with values > or < some absolute threshold).
So far so good, with one slight issue - the axis break ends up being exactly on a data point on each side, which makes it harder to read on the axis, and also, the datapoints themselves end up split in two, which is kind of awkward.
I would like the axis break to instead be between datapoints, something like:
----(last value before break)--/ /--(first value after break)----
Is there a way to do this?
The breakpoints are determined with set_xlim, and I'm not sure if there's a way to do move them off the datapoints with a categorical x-axis...
sort_res_h = sort_res_a[sort_res_a > threshold]
sort_res_l = sort_res_a[sort_res_a < -threshold]
ax0.errorbar(sort_res_a.index, sort_res_a, yerr=chg_dpm_err, fmt='o')
ax1.errorbar(sort_res_a.index, sort_res_a, yerr=chg_dpm_err, fmt='o')
ax0.set_xlim(xmax=sort_res_h.index[-1])
ax1.set_xlim(xmin=sort_res_l.index[0])
I am going to share what I have been able to complete so far, although it is not a flawless solution. But maybe this will help you in any case. I would propose that you set your xaxis limits using the ticks positions, instead of the data. The problem is that if you take ticks as provided by default by matplotlib, sometimes there are more ticks than those that you see (for example there could be ticks before the minimum value in the xaxis or after the maximum). As in your case you seem to be setting the ticks, I think this should work (Replace the way you set your axes limits by this. I only provide the code for the ax0):
# First we get current ticks positions
ax0_xticks_positions = ax0.get_xticks()
# then we get the distance between two ticks
ax0_ticks_distance = ax0_xticks_positions[1] - ax0_xticks_positions[0]
# percentage of tick separation that we want the axis to extend beyond/before the last/first tick
percentage_add = 0.5
# set the xlim to the last tick position plus a percentage of tick distance
ax0.set_xlim(xmax = ax0_xticks_positions[-1] + percentage_add*ax0_ticks_distance)
You can play around with percentage_add until you find a value that suits you. For ax1 you would have to use the first tick:
ax1.set_xlim(xmin = ax1_xticks_positions[0] - percentage_add*ax0_ticks_distance)
The problem of this solution, is if the tick you use to fix the limit is outside the current axis limits. That would make the breakpoint go further than you would expect. To solve that, you can compare the tick position (for example ax0_xticks_positions[-1]) to the applicable axis limit (following the example ax0.get_xlim()[-1]). If the tick position is larger than the limit, you would have to use the second to last tick ax0_xticks_positions[-2]
I am relatively new to coding, so I apologize beforehand for this simple question:
I want to plot 2week candlesticks.
After I resampled my dataset in 2 week chunks I plotted the results. Unfortunately, matplotlib plots the chart with the complete date range, meaning that there are 14 day gaps between each candle. I already have tried to use ax.xaxis.set_major_locator(WeekdayLocator(byweekday=MO, interval=2)) but this just formats the labels of the x-axis, not the used values.
The Code:
fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2)
ax.xaxis.set_major_formatter(weekFormatter)
candlestick_ohlc(ax, zip(mdates.date2num(quotes.index.to_pydatetime()),
quotes['open'], quotes['high'],
quotes['low'], quotes['close']),
width=0.6)
plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
plt.show()
Heres the result:
So how can I create a continuous graph where the candlesticks are closer to each other ?
[EDIT]
Wow, the simple solution is to put the width higher... I am really sorry for this. It was my first post here :D
I think the problem is with minor locator, which makes smaller marks on x axis every day. You can use ax.xaxis.minorticks_off() to disable them.
[EDIT]
Hmm, now that I reread the question I think that you want candlesticks to be wider. There is width parameter to do just so.
I'm using Matplotlib to plot data on Ubuntu 15.10. My y-axis has numeric values and my x-axis timestamps.
I'm having the problem that the date labels intersect with each other making it look bad. How do I increase the distance between the x-axis ticks/labels to be evenly spaced still? Since the automatic selection of ticks was bad I'm okay with manually setting the amount of date ticks. Any other solution is appreciated, too.
Besides, I'm using the following DateFormatter:
formatter = DateFormatter('%m/%d/%y')
axis = plt.gca()
axis.xaxis.set_major_formatter(formatter)
You could add the following to your code:
plt.gcf().autofmt_xdate()
Which automatically formats the x axis for you (rotates the labels to something like 30 degrees etc).
You can also manually set the amount of x ticks that show on your x-axis to avoid it getting crowded, by using the following:
max_xticks = 10
xloc = plt.MaxNLocator(max_xticks)
ax.xaxis.set_major_locator(xloc)
I personally use both together as it makes the graph look much nicer when using dates.
You can simply set the locations you want to be labeled:
axis.set_xticks(x[[0, int(len(x)/2), -1]])
where x would be your array of timestamps