How can I add dates to bar charts when the data I am plotting are matrices?

1 次查看(过去 30 天)
I am trying to plot a matrix of N * 7 elements in a bar chart. N are different dates for which I have 7 variables under study. If I have N around 8, the graph looks nice and it shows what I want. Namely, the date for the group of variables on the x axis. However, if I have N = 20 or bigger it only shows the first five dates spanning the whole x-axis.
The code I am using right now is the following:
width = 6; % Width in inches
height = 3; % Height in inches
%FIGURE 1: Sectors Jump Days
fig1=figure(1);
pos = get(gcf, 'Position');
set(gcf, 'Position', [pos(1) pos(2) width*100, height*100])
bar(AverageTime)
set(gca,'XTickLabel',dayIndjumpStr)
legend('Primary','Manufacturing','Transport','Trade','Finance','Services','PA')
and dayIndjumpstr is a cell array. Thank you very much.

回答(1 个)

BhaTTa
BhaTTa 2024-9-13
@Alessandro Pollastri, it seems like the issue you're encountering is related to the x-axis tick labels not displaying all the dates when N is large. This is a common problem when plotting a large number of categories on the x-axis. Here's how you can address it:
  1. Rotate the x-axis labels: Rotating the labels can help fit more labels into the space.
  2. Set the x-axis ticks manually: If you have too many dates, you might want to display fewer labels for better readability.
  3. Increase the figure size: Making the figure larger can sometimes help accommodate more labels.
Here's an updated version of your code incorporating these suggestions:
% Example data initialization
N = 20; % Number of dates
AverageTime = rand(N, 7); % Random data for demonstration purposes
% Example date labels
dayIndjumpStr = arrayfun(@(x) datestr(now + x, 'mm/dd/yyyy'), 0:N-1, 'UniformOutput', false);
% Plotting
width = 10; % Increased width in inches for better spacing
height = 5; % Increased height in inches
fig1 = figure(1);
pos = get(gcf, 'Position');
set(gcf, 'Position', [pos(1) pos(2) width*100, height*100]);
bar(AverageTime);
% Rotate x-axis labels for better readability
xtickangle(45);
% Set the x-axis labels
set(gca, 'XTick', 1:length(dayIndjumpStr), 'XTickLabel', dayIndjumpStr);
legend('Primary', 'Manufacturing', 'Transport', 'Trade', 'Finance', 'Services', 'PA');

类别

Help CenterFile Exchange 中查找有关 Bar Plots 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by