Shayan
Shayan

Reputation: 6385

How to shrink color bar of heatmap plot to fit the dimension of the plot in Julia?

I have the following heatmap plot:

using DataFrames, Plots, Statistics, RDatasets

iris_df = dataset("datasets", "iris")
cor_mat = cor(Matrix(iris_df[:, 1:4]), dims=1)
col_names = names(iris_df)[1:end-1]
heatmap(
  col_names, col_names, cor_mat,
  rightmargin=20Plots.mm,
  leftmargin=10Plots.mm,
  aspect_ratio=:equal,
  size=(700, 700),
  title="Correlation heatmap between 4 features of the Iris dataset",
  xlabel="Features", ylabel="Features",
  colorbar_title="Correlation",
  color=:bluesreds,
  framestyle=:box,
  titlefont=font(12)
)
plot!(dpi=300)

enter image description here

How can I shrink it to fit the plot?
Plots version: v1.37.2

Upvotes: 0

Views: 475

Answers (3)

Rafael_Guerra
Rafael_Guerra

Reputation: 130

With default gr() backend, use keyword argument: lims=(0,4):

gr()

heatmap(
  col_names, col_names, cor_mat,
  aspect_ratio=:equal,
  size=(1000, 1000),
  title="\n"^6 * "Correlation heatmap between 4 features of the Iris dataset",
  xlabel="Features", ylabel="Features",
  colorbar_title="Correlation",
  color=:bluesreds,
  framestyle=:box,
  titlefont=font(15),
  lims=(0,4),
  dpi=300
)

enter image description here

Upvotes: 1

Shayan
Shayan

Reputation: 6385

using the pyplot() as the backend and moving the dpi inside of the heatmap function solves the problem:

pyplot()

heatmap(
  col_names, col_names, cor_mat,
  rightmargin=20Plots.mm,
  leftmargin=10Plots.mm,
  aspect_ratio=:equal,
  size=(700, 700),
  title="Correlation heatmap between 4 features of the Iris dataset",
  xlabel="Features", ylabel="Features",
  colorbar_title="Correlation",
  color=:bluesreds,
  framestyle=:box,
  titlefont=font(12),
  dpi=300
)

enter image description here

But when I try to save the figure using the savefig function, it saves the unshrinked version :)


Update 12/20/2022
Inspired by Rafael's answer, using lims = (0, 4)* in the heatmap function on the pyplot backend solves the issue completely even in the result of savefig:

pyplot()

heatmap(
  col_names, col_names, cor_mat,
  aspect_ratio=:equal,
  size=(1000, 1000),
  title="Correlation heatmap between 4 features of the Iris dataset",
  xlabel="Features", ylabel="Features",
  colorbar_title="Correlation",
  color=:bluesreds,
  framestyle=:box,
  titlefont=font(15),
  lims=(0,4),
  dpi=300
)

enter image description here *The reason behind 4 is the number of squares in the vertical axes is 4.

Upvotes: 1

LloydNA
LloydNA

Reputation: 11

I faced the same issue once but with a regular plot, the fix that i did was to get the higher value of both 'x' and 'y' coordinates and make an initial plot like this:

toSave = plot([X],[Y])

Then pushed the plot that i wanted with

plot!()

Upvotes: 0

Related Questions