Expand Spacing Between Tick Marks on X Axis

Expand spacing between tick marks on x axis

It's not the plot function that determines the aspect ratio of the interactive plotting device. Each of the 3 major branches of R has its own default interactive device: Macs has quartz(), Windows have (I thought window() but checking its help page I am clearly wrong, and checking ?dev.interactive it is revealed that the correct function is windows()), and Linux, x11() or X11(). If you want to open a device with different dimension than default, you need to issue a command with different height and width values than default (or you can stretch an existing window if your GUI supports that action):

  quartz(height = 5, width = 10)
A <- c(5,4,6,7,3,8,4,2)
B <- c(2005:2012)
plot(B, A, type="l")

Sample Image

If you would learn more about the R graphics model you should read: ?Devices.

After failing to remember the windows interactive device name I see that this might be a cross-platform hack using the fact that the options function can provide access to the default device:

options()$device(height=5, width=10)

How to change spacing between ticks in matplotlib?

The spacing between ticklabels is exclusively determined by the space between ticks on the axes. Therefore the only way to obtain more space between given ticklabels is to make the axes larger.

In order to determine the space needed for the labels not to overlap, one may find out the largest label and multiply its length by the number of ticklabels. One may then adapt the margin around the axes and set the calculated size as a new figure size.

import numpy as np
import matplotlib.pyplot as plt

N = 150
data = np.linspace(0, N, N)

plt.plot(data)

plt.xticks(range(N)) # add loads of ticks
plt.grid()

plt.gca().margins(x=0)
plt.gcf().canvas.draw()
tl = plt.gca().get_xticklabels()
maxsize = max([t.get_window_extent().width for t in tl])
m = 0.2 # inch margin
s = maxsize/plt.gcf().dpi*N+2*m
margin = m/plt.gcf().get_size_inches()[0]

plt.gcf().subplots_adjust(left=margin, right=1.-margin)
plt.gcf().set_size_inches(s, plt.gcf().get_size_inches()[1])

plt.savefig(__file__+".png")
plt.show()

Sample Image

Note that if the figure shown in the plotting window is larger than the screen, it will be shrunk again, so the resized figure is only shown in its new size when saved. Or, one may choose to incorporate it in some window with scrollbars as shown in this question: Scrollbar on Matplotlib showing page

Matplotlib increase spacing between points on x-axis

Firstly, it's hard to know exactly what's happening, without your data, so I had to create dummy data and adjust for your variables, 'self.identifier', and 'xticks' given that we don;t know what those are.

That being said, the function you're looking for is

plt.tick_params(axis='x', which='major', labelsize=__)

as seen in the code below:

import numpy as np
import matplotlib.pyplot as plt

#make dummy data
x=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40]
y=np.random.rand(len(x))

plt.figure()
plt.plot(x, y)
plt.bar(x, y, alpha=0.2)
plt.title(f"średnia cena produktu, według kontrahentów")
plt.xlabel("kontrahent")
plt.ylabel("cena")
plt.xticks(x, [str(i) for i in y], rotation=90)

#set parameters for tick labels
plt.tick_params(axis='x', which='major', labelsize=3)

plt.tight_layout()

R how to increase spacing between X and Y axis value labels

I've got to agree with user2974951. If you use the below code, you can adjust the width and height values to until there's enough spacing between the tick labels.

my_plot <- ggplot(data = e_2020_Voting_Machines_Per_State) +
geom_point(mapping = aes(x = State_Abbr, y = totalMachines)) + coord_flip()

tiff("my_plot.tiff", width = 8, height =6, units = "cm", res = 300)
print(my_plot)
dev.off()

Or, you can include + element_text(size = 7) to your original ggplot() code to reduce the text size until they're all readable.

Matplotlib: How to increase space between tickmarks (or reduce number of tickmarks)?

The tickspacing is solemnly determined by the difference of subsequent tick locations. Matplotlib will usually find nice tick locations for you automatically.

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

df = pd.DataFrame({"time" : np.arange("2010-01-01", "2012-01-01", dtype="datetime64[M]"),
"value" : np.random.randint(0,10,size=24)})
fig, ax = plt.subplots()
ax.plot(df['time'], df['value'])
plt.setp(ax.get_xticklabels(), rotation=45, ha="right")

plt.show()

Sample Image

If you don't like those you may supply custom ones, via a ticker.

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
import numpy as np

df = pd.DataFrame({"time" : np.arange("2010-01-01", "2012-01-01", dtype="datetime64[M]"),
"value" : np.random.randint(0,10,size=24)})
fig, ax = plt.subplots()
ax.plot(df['time'], df['value'])
ax.xaxis.set_major_locator(mdates.MonthLocator((1,7)))
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%b"))
plt.setp(ax.get_xticklabels(), rotation=45, ha="right")

plt.show()

Sample Image

If you really want your dates to be categorical, you may use a MultipleLocator. E.g. to tick every 5th category,

import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import pandas as pd
import numpy as np

df = pd.DataFrame({"time" : np.arange("2010-01-01", "2012-01-01", dtype="datetime64[M]"),
"value" : np.random.randint(0,10,size=24)})
df["time"] = df["time"].dt.strftime('%Y-%m')

fig, ax = plt.subplots()
ax.plot(df['time'], df['value'])
ax.xaxis.set_major_locator(mticker.MultipleLocator(5))
plt.setp(ax.get_xticklabels(), rotation=45, ha="right")

plt.show()

Sample Image

Change the spacing of tick marks on the axis of a plot?

There are at least two ways for achieving this in base graph (my examples are for the x-axis, but work the same for the y-axis):

  1. Use par(xaxp = c(x1, x2, n)) or plot(..., xaxp = c(x1, x2, n)) to define the position (x1 & x2) of the extreme tick marks and the number of intervals between the tick marks (n). Accordingly, n+1 is the number of tick marks drawn. (This works only if you use no logarithmic scale, for the behavior with logarithmic scales see ?par.)

  2. You can suppress the drawing of the axis altogether and add the tick marks later with axis().

    To suppress the drawing of the axis use plot(... , xaxt = "n").

    Then call axis() with side, at, and labels: axis(side = 1, at = v1, labels = v2). With side referring to the side of the axis (1 = x-axis, 2 = y-axis), v1 being a vector containing the position of the ticks (e.g., c(1, 3, 5) if your axis ranges from 0 to 6 and you want three marks), and v2 a vector containing the labels for the specified tick marks (must be of same length as v1, e.g., c("group a", "group b", "group c")). See ?axis and my updated answer to a post on stats.stackexchange for an example of this method.



Related Topics



Leave a reply



Submit