How can I plot data from a text file--an array of numbers versus an array of strings?
조회 수: 28 (최근 30일)
이전 댓글 표시
I want to plot data from a text file, where x is an array of categories (strings) and y is an array of numbers. I have followed examples online, but so far nothing is working. If anyone could please point me in the right direction, I would be very grateful.
For example, after I have read in my array of strings and print it out, I get:
'Dry'
'Wet'
'Saturated'
'Wet'
'Wet'
'Dry'
The array of numbers is the same size as the array of strings (i.e., there's a value to match each string entry):
1
2
3
4
5
6
1. I have tried (among other things):
labels = {stringArray};
plot(numberArray, 'o', 'MarkerSize', 5)
set(gca, 'XTickLabel',labels)
But get this error:
Error using matlab.graphics.axis.Axes/set
While setting property 'XTickLabel' of class 'Axes':
Cell array can only contain character vectors or numbers.
Error in metadata_plots_vi_text (line 38)
set(gca, 'XTickLabel',labels)
2. I also tried writing this for "labels"
labels = [WRB_ISRIC];
This gives me a plot where the X axis has "Wet Wet Wet Dry Saturated" instead of "Wet Dry Saturated."
Does anyone know an alternative?
댓글 수: 0
채택된 답변
Adam Danz
2020년 9월 15일
편집: Adam Danz
2020년 9월 15일
Here's a variety of ways to use the strings as axis ticks.
After a second look, you're probably looking for the last method.
stringArray = {
'Dry'
'Wet'
'Saturated'
'Wet'
'Wet'
'Dry'};
numberArray = [
1
2
3
4
5
6];
clf
s(1) = subplot(4,1,1);
plot(numberArray, categorical(stringArray), 'o-');
title('plot()')
s(2) = subplot(4,1,2);
stem(numberArray, categorical(stringArray), 'o-');
title('stem()')
s(3) = subplot(4,1,3);
[n,cats]= histcounts(categorical(stringArray));
bar(categorical(cats),n);
title('bar()')
s(4) = subplot(4,1,4);
plot(numberArray, 'o', 'MarkerSize', 5)
set(s(4), 'XTick', 1:numel(numberArray), 'XTickLabel', stringArray)
title('XTick & XTickLabel')
s(5) = subplot(5,1,5);
plot(categorical(stringArray), numberArray, 'o', 'MarkerSize', 5)
title('plot(categorical, y)')
set(s(1:2),'XTick',1:6,'XLim',[0,7])
For earlier releases of Matlab that did not support automatic assignment of categorical tick labels,
cats = categorical(stringArray);
catsUnq = categories(cats);
plot(categorical(stringArray), numberArray, 'o', 'MarkerSize', 5)
set(gca, 'XTick', 1:numel(catsUnq), 'XTickLabel', catsUnq)
댓글 수: 13
추가 답변 (1개)
Xavier
2020년 9월 15일
Try using
set(gca, 'XTickLabel',stringArray)
instead, you don't need a cell array to have labels
댓글 수: 3
Adam Danz
2020년 9월 15일
Whenever setting XTickLabel, also set XTick. Otherwise, you risk a mismatch between the number of ticks and labels and Matlab will either wrap the labels or skip the extras by default.
set(gca, 'XTick', 1:numel(stringArray), 'XTickLabel',stringArray)
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Distribution Plots에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!